gpt4 book ai didi

python-3.x - python 3 : print float precision without zero followed

转载 作者:行者123 更新时间:2023-12-04 20:29:59 24 4
gpt4 key购买 nike

这个问题在这里已经有了答案:





Formatting floats without trailing zeros

(20 个回答)


3年前关闭。




例如

x = 1.23
print("%.3f" % x)

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

编辑:
我想要一个在 处打印浮点数的函数极限精度如果未达到给定的限制,则不会打印零

最佳答案

如果你想输出最多 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

输出:
1.23
1.234
1.1
1.785

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

关于python-3.x - python 3 : print float precision without zero followed,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48476908/

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