gpt4 book ai didi

python float to string 没有精度损失

转载 作者:太空宇宙 更新时间:2023-11-04 00:48:50 26 4
gpt4 key购买 nike

对于 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 符号也是可能的)

最佳答案

使用 Python 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 位数字应该足以表达 double IEEE 754 float 的完整精度(20 位数字表示您可能会遇到的 80 位扩展精度)。

关于python float to string 没有精度损失,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38055000/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com