[英]Python decimal places value fixed
我试图在浮点数中始终保留 2 个小数位,例如:
3.28329482394283104923804 -> 3.28
3.0 -> 3.00
3 -> 3.00
使用round(x,2)
,但问题是第二种情况(3.0 -> 3.00)
返回3.0
而不是3.00
。 我能做什么?
我有这些值,我正在创建一个这样的字符串:
final = "The number is " + str(number)
如果您只想对数字进行四舍五入以获得要显示的字符串,则可以这样做,
尝试这个:
print("{:.2f}".format(3.28329482394283104923804))
输出3.28
print("{:.2f}".format(3.0))
输出3.00
print("{:.2f}".format(3))
输出3.00
或者在 python 中使用 fstrings,
print(f'{3.28329482394283104923804:.2f}')
输出3.28
print(f'{3.0:.2f}')
输出3.00
print(f'{3:.2f}')
输出3.00
更新(正如您在评论中所问):
final = f"The number is {number:.2f}"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.