我希望a四舍五入到13.95。我试过用圆形,但我得到:
>>> a
13.949999999999999
>>> round(a, 2)
13.949999999999999
有关标准库Decimal类的类似问题,请参阅How can I format a Decimal to always show 2 Decimal places?。
我希望a四舍五入到13.95。我试过用圆形,但我得到:
>>> a
13.949999999999999
>>> round(a, 2)
13.949999999999999
有关标准库Decimal类的类似问题,请参阅How can I format a Decimal to always show 2 Decimal places?。
当前回答
正如Matt所指出的,Python 3.6提供了f字符串,它们也可以使用嵌套参数:
value = 2.34558
precision = 2
width = 4
print(f'result: {value:{width}.{precision}f}')
显示结果:2.35
其他回答
在Python中,可以使用格式运算符将值舍入到两位小数:
print(format(14.4499923, '.2f')) // The output is 14.45
它正按照您的指示执行,并且工作正常。阅读更多关于浮点混淆的内容,并尝试使用十进制对象。
使用Decimal对象和round()方法的组合。
Python 3.7.3
>>> from decimal import Decimal
>>> d1 = Decimal (13.949999999999999) # define a Decimal
>>> d1
Decimal('13.949999999999999289457264239899814128875732421875')
>>> d2 = round(d1, 2) # round to 2 decimals
>>> d2
Decimal('13.95')
正如Matt所指出的,Python 3.6提供了f字符串,它们也可以使用嵌套参数:
value = 2.34558
precision = 2
width = 4
print(f'result: {value:{width}.{precision}f}')
显示结果:2.35
我觉得最简单的方法是使用format()函数。
例如:
a = 13.949999999999999
format(a, '.2f')
13.95
这将产生一个浮点数,作为四舍五入到两个小数点的字符串。