[英]Python decimal places value fixed
I'm trying to have always 2 decimal places in a float number, eg:我试图在浮点数中始终保留 2 个小数位,例如:
3.28329482394283104923804 -> 3.28
3.0 -> 3.00
3 -> 3.00
with round(x,2)
, but the problem is that the second case (3.0 -> 3.00)
is returning 3.0
instead of 3.00
.使用round(x,2)
,但问题是第二种情况(3.0 -> 3.00)
返回3.0
而不是3.00
。 What can I do?我能做什么?
I have the values and I'm creating a string like this:我有这些值,我正在创建一个这样的字符串:
final = "The number is " + str(number)
If you just want to round off the number to obtain a string to display, you can do,如果您只想对数字进行四舍五入以获得要显示的字符串,则可以这样做,
Try this:尝试这个:
print("{:.2f}".format(3.28329482394283104923804))
outputs 3.28
print("{:.2f}".format(3.28329482394283104923804))
输出3.28
print("{:.2f}".format(3.0))
outputs 3.00
print("{:.2f}".format(3.0))
输出3.00
print("{:.2f}".format(3))
outputs 3.00
print("{:.2f}".format(3))
输出3.00
OR using the fstrings in python,或者在 python 中使用 fstrings,
print(f'{3.28329482394283104923804:.2f}')
outputs 3.28
print(f'{3.28329482394283104923804:.2f}')
输出3.28
print(f'{3.0:.2f}')
outputs 3.00
print(f'{3.0:.2f}')
输出3.00
print(f'{3:.2f}')
outputs 3.00
print(f'{3:.2f}')
输出3.00
UPDATE (as you asked in comments):更新(正如您在评论中所问):
final = f"The number is {number:.2f}"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.