Skip to main content
 首页 » 编程设计

python之为什么 Python 在四舍五入时不包括我在小数点后指定的位数

2025年05月04日8yjmyzz

例如,

a = 5 * 6.2 
print (round(a, 2) 

输出为 31.0。我本来预计 31.00。

b = 2.3 * 3.2 
print (round(b, 3)) 

输出为 7.36。我本以为是 7.360。

请您参考如下方法:

您混淆了舍入和格式。四舍五入产生一个新的 float 对象,其值经过四舍五入,仍将以与任何其他 float 相同的方式打印:

>>> print(31.00) 
31.0 

使用 format() function如果您需要生成具有特定小数位数的字符串:

>>> print(format(31.0, '.2f')) 
31.00 

参见 Format Specification Mini-Language您可以使用哪些选项的部分。

如果该值是较大字符串的一部分,您可以使用 str.format() method使用相同的格式规范将值嵌入到字符串模板中:

>>> a = 5 * 6.2 
>>> print('The value of "a" is {:.2f}'.format(a))