这是使用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