Python 3:不带零的打印浮点精度

Arm*_*ino 5 floating-point python-3.x

例如

x = 1.23
print("%.3f" % x)
Run Code Online (Sandbox Code Playgroud)

输出将是“ 1.230”,我想要“ 1.23”。有什么办法吗?谢谢。

编辑:我想要一个函数,将以极限精度打印浮点,并且如果没有达到给定的极限,则不会打印零

Pat*_*ner 3

如果要输出最多 3 位数字但不包含 0,则需要格式化为 3 位数字和rstrip零:

for n in [1.23,1.234,1.1,1.7846]:
    print('{:.3f}'.format(n).rstrip("0"))  # add .rstrip(".") to remove the . for 3.00003
Run Code Online (Sandbox Code Playgroud)

输出:

1.23
1.234
1.1
1.785
Run Code Online (Sandbox Code Playgroud)

快速阅读这里的 python 3 格式: https: //pyformat.info/#number或这里: https: //docs.python.org/3.1/library/string.html#format-examples