我希望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?。
当前回答
大多数数字不能用浮点数精确表示。如果你想舍入这个数字,因为这是你的数学公式或算法所要求的,那么你想使用舍入。如果您只想将显示限制为某一精度,那么甚至不要使用舍入,只需将其格式化为字符串即可。(如果您想用其他舍入方法显示,并且有吨,则需要混合使用这两种方法。)
>>> "%.2f" % 3.14159
'3.14'
>>> "%.2f" % 13.9499999
'13.95'
最后,也许最重要的是,如果你想要精确的数学,那么你根本不需要浮点数。通常的例子是处理货币,并将“美分”存储为整数。
其他回答
如果您想处理金钱,请使用Python十进制模块:
from decimal import Decimal, ROUND_HALF_UP
# 'amount' can be integer, string, tuple, float, or another Decimal object
def to_money(amount) -> Decimal:
money = Decimal(amount).quantize(Decimal('.00'), rounding=ROUND_HALF_UP)
return money
它正按照您的指示执行,并且工作正常。阅读更多关于浮点混淆的内容,并尝试使用十进制对象。
对于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文档中的字符串格式链接。
关于选项一的更多信息,这个链接就足够了,并提供了各种标志的信息。
引用:将浮点数转换为特定精度,然后复制为字符串
from decimal import Decimal
def round_float(v, ndigits=2, rt_str=False):
d = Decimal(v)
v_str = ("{0:.%sf}" % ndigits).format(round(d, ndigits))
if rt_str:
return v_str
return Decimal(v_str)
结果:
Python 3.6.1 (default, Dec 11 2018, 17:41:10)
>>> round_float(3.1415926)
Decimal('3.14')
>>> round_float(3.1445926)
Decimal('3.14')
>>> round_float(3.1455926)
Decimal('3.15')
>>> round_float(3.1455926, rt_str=True)
'3.15'
>>> str(round_float(3.1455926))
'3.15'
在Python 2.7中:
a = 13.949999999999999
output = float("%0.2f"%a)
print output