【问题标题】:How to get first 4 digits after the 0s in a decimal but keeping 0s • Python如何获取小数点中 0 后的前 4 位但保留 0 • Python
【发布时间】:2022-01-04 22:21:04
【问题描述】:

我需要十进制前 0 之后的前 4 位数字,同时在输出中保留 0 而不获取科学记数法。

想拿 0.0000000000000000000000634546534 并得到 0.00000000000000000000006345 但不是 6.345e-23.

但也想拿 231.00942353246 并得到 231.009423.

谢谢。

【问题讨论】:

  • 2.45676 怎么样,你想要 2.4567 还是四舍五入到 2.4568?
  • 两者都有一个选项会很棒,但如果我必须选择 2.4567。
  • 请澄清您的具体问题或提供其他详细信息以准确突出您的需求。正如目前所写的那样,很难准确地说出你在问什么。

标签: python-3.x floating-point format decimal scientific-notation


【解决方案1】:

这是使用decimal module 的一种方式。

import decimal

example = 0.0000000000000000000000634546534

x = decimal.Decimal(example)
sign = x.as_tuple().sign
digits = x.as_tuple().digits
exponent = x.as_tuple().exponent

figs = 4
result = decimal.Decimal((sign, digits[:figs], len(digits)+(exponent)-figs))

precision = -1 * (len(digits) + (exponent) - figs) # for this example: -1 * (99 + (-121) - 4)
print("{:.{precision}f}".format(float(result), precision=precision))

结果:

0.00000000000000000000006345

请注意,Decimal 存储 99 位数字,因为浮点不精确。 example 变量包含一个本质上不精确的浮点值(由于初始化值)。没有办法解决这个问题,除非您能够将原始浮点值表示为一个字符串,您可以使用它来初始化 example 变量。

在某些情况下,显示的第 4 位数字是错误的,因为在浮点表示中,该数字表示为一个较小的数字,而下一个数字是 9,例如。为了解决这个问题,我们还要再抓取一位数字以用于舍入。这应该适用于大多数情况,因为不精确度应该在最接近的舍入阈值之内。

result = decimal.Decimal((0, digits[:figs + 1], len(digits)+(exponent)-figs-1))

最后,为了处理小数点前有数字的情况,我们可以简单地存储它,删除它,然后重新添加它:

whole_number_part = int(example)
example -= whole_number_part
...
result += whole_number_part

总之,我们得到:

import decimal

example = 231.00942353246

whole_number_part = int(example)

example -= whole_number_part

x = decimal.Decimal(example)
sign = x.as_tuple().sign
digits = x.as_tuple().digits
exponent = x.as_tuple().exponent

figs = 4
result = decimal.Decimal((0, digits[:figs + 1], len(digits)+(exponent)-figs-1))
result += whole_number_part

precision = -1 * (len(digits) + (exponent) - figs)
print("{:.{precision}f}".format(float(result), precision=precision))

结果:

231.009423

【讨论】:

    猜你喜欢
    • 2022-01-23
    • 1970-01-01
    • 1970-01-01
    • 2022-06-26
    • 1970-01-01
    • 1970-01-01
    • 2022-10-12
    • 2015-09-16
    相关资源
    最近更新 更多