使用round()显示最终的零
举个例子,我想让下面的结果显示为 5.90
test = round(5.9, 2)
print(test)
相关问题:
- 暂无相关问题
3 个回答
-1
这个在Python 2和Python 3中都能用
n = 5.9
print('%.2f' % n) # -> 5.90
在Python 3中也能用
print('{:.2f}'.format(n)) # -> 5.90
而且从Python 3.7开始也能用:
print(f'{n:.2f}') # -> 5.90
0
你可以用 %.2f 来代替.. 比如说:
test = round(5.9, 2)
print("%.2f"%test)
这样输出的结果会是 5.90。你可以把 2 换成你想要的小数点后面的数字个数。
2
你不能控制浮点数在打印时显示多少位小数。如果想要控制这个,就需要把浮点数格式化成字符串,然后再打印出来。
举个例子:
(另外:把一个小数点后有1位的数字四舍五入到2位小数是没有意义的。)
test = 5.9
print(f"{test:.2f}")
输出:
5.90
你可以在这里了解更多关于字符串格式化的内容: https://docs.python.org/3/library/string.html#format-specification-mini-language