我希望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?。
当前回答
内置round()在Python 2.7或更高版本中运行良好。
例子:
>>> round(14.22222223, 2)
14.22
查看文档。
其他回答
下面是使用format函数的简单解决方案。
float(format(num, '.2f'))
注意:我们将数字转换为浮点数,因为format方法返回字符串。
它正按照您的指示执行,并且工作正常。阅读更多关于浮点混淆的内容,并尝试使用十进制对象。
正如Matt所指出的,Python 3.6提供了f字符串,它们也可以使用嵌套参数:
value = 2.34558
precision = 2
width = 4
print(f'result: {value:{width}.{precision}f}')
显示结果:2.35
我们有多种选择:
选项1:
x = 1.090675765757
g = float("{:.2f}".format(x))
print(g)
选项2:内置round()支持Python 2.7或更高版本。
x = 1.090675765757
g = round(x, 2)
print(g)
让我举一个Python 3.6的f-string/模板字符串格式的例子,我认为它非常整洁:
>>> f'{a:.2f}'
它也适用于较长的示例,使用运算符,不需要括号:
>>> print(f'Completed in {time.time() - start:.2f}s')