【发布时间】:2016-10-29 12:41:48
【问题描述】:
对于 python 3,我想将浮点数转换为字符串,长度可能不同(即位数),但具有完整的精度。
在任何情况下我都需要有一个小数点:
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 符号也是可能的)
【问题讨论】:
-
我的意思是,我会使用
endswith而不是.find < 0,但除此之外它看起来还不错。这对于 codereview 可能会更好,因为“更优雅”并不是我们可以给你的真正客观的东西。 -
@MorganThrapp
endswith如何解决这个问题? -
@Selcuk 哦,你是对的。抱歉,时间还早。
-
我会使用
'.' in out
标签: python python-3.x floating-point