python浮动到字符串而没有精度损失

时间:2016-06-27 13:17:03

标签: python python-3.x floating-point

对于python 3,我想将一个float转换为一个字符串,可能有不同的长度(即位数),但是具有完全的精度。

在任何情况下我都需要有一个小数点:

1    -> '1.'
1/10 -> '0.1000000000000000055511151231257827021181583404541015625'

目前我的代码是:

from decimal import Decimal
def formatMostSignificantDigits(x):
    out = str(Decimal(x))
    if out.find('.') < 0:
        out += '.'
    return out

可以更优雅地完成吗? (e表示法也是可能的)

2 个答案:

答案 0 :(得分:2)

使用Pythons string formatting functions

>>> x = 1.0; '{:.55f}'.format(x)
'1.0000000000000000000000000000000000000000000000000000000'
>>> x = 1/10; '{:.55f}'.format(x)
'0.1000000000000000055511151231257827021181583404541015625'

如果您希望能够提供整数(例如1),请使用'{:.55f}'.format(float(x))

如果要删除任何尾随零,请使用'{:.55f}'.format(x).rstrip('0')

请注意,该点之后的55位小数是过度杀戮(但它是您在问题中显示的内容); 16位数应足以表示双精度IEEE 754浮点数的完整精度(对于您可能遇到的80位扩展精度,20位数字)。

答案 1 :(得分:1)

为什么使用Decimal,你可以使用:

x = 0.1
s = str(x)
print(s)   # this prints '0.1'

但是如果你使用Decimal而不是这个:

out = str(Decimal(x))
if out.find('.') < 0:
    out += '.'
return out

你可以使用:

return Decimal(x).__str__()

编辑1:

浮点精度的好模块也是bigfloat:

from bigfloat import BigFloat
x = 0.1
print(BigFloat(x, precision(300)).__str__())
# thsi will print'0.10000000000000000555111512312578270211815834045410156250000000000000000000000000000000000000'
# but if you use this:
print(BigFloat(x.__str__(), precision(300)).__str__())
# it can be precise as much as you want
print(BigFloat(x.__str__(), precision(100000)).__str__()) # try this
相关问题