我希望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?。
当前回答
下面是使用format函数的简单解决方案。
float(format(num, '.2f'))
注意:我们将数字转换为浮点数,因为format方法返回字符串。
其他回答
在Python 2.7中:
a = 13.949999999999999
output = float("%0.2f"%a)
print output
内置round()在Python 2.7或更高版本中运行良好。
例子:
>>> round(14.22222223, 2)
14.22
查看文档。
对于Python<3(例如2.6或2.7),有两种方法可以实现。
# Option one
older_method_string = "%.9f" % numvar
# Option two (note ':' before the '.9f')
newer_method_string = "{:.9f}".format(numvar)
但请注意,对于3以上的Python版本(例如3.2或3.3),首选选项二。
有关选项2的更多信息,我建议使用Python文档中的字符串格式链接。
关于选项一的更多信息,这个链接就足够了,并提供了各种标志的信息。
引用:将浮点数转换为特定精度,然后复制为字符串
它正按照您的指示执行,并且工作正常。阅读更多关于浮点混淆的内容,并尝试使用十进制对象。
为了修复Python和JavaScript等类型动态语言中的浮点,我使用了这种技术
# For example:
a = 70000
b = 0.14
c = a * b
print c # Prints 980.0000000002
# Try to fix
c = int(c * 10000)/100000
print c # Prints 980
您还可以按以下方式使用Decimal:
from decimal import *
getcontext().prec = 6
Decimal(1) / Decimal(7)
# Results in 6 precision -> Decimal('0.142857')
getcontext().prec = 28
Decimal(1) / Decimal(7)
# Results in 28 precision -> Decimal('0.1428571428571428571428571429')