我希望a四舍五入到13.95。我试过用圆形,但我得到:

>>> a
13.949999999999999
>>> round(a, 2)
13.949999999999999

有关标准库Decimal类的类似问题,请参阅How can I format a Decimal to always show 2 Decimal places?。


当前回答

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'

其他回答

我看到的答案对浮点数(52.15)不起作用。经过一些测试,我使用的解决方案是:

import decimal
        
def value_to_decimal(value, decimal_places):
    decimal.getcontext().rounding = decimal.ROUND_HALF_UP  # define rounding method
    return decimal.Decimal(str(float(value))).quantize(decimal.Decimal('1e-{}'.format(decimal_places)))

(将“value”转换为float和string非常重要,这样一来,“value”可以是float、decimal、integer或string类型!)

希望这对任何人都有帮助。

请尝试以下代码:

>>> a = 0.99334
>>> a = int((a * 100) + 0.5) / 100.0 # Adding 0.5 rounds it up
>>> print a
0.99

有新的格式规范,字符串格式规范迷你语言:

您可以执行以下操作:

"{:.2f}".format(13.949999999999999)

注1:上面返回一个字符串。为了获得float,只需用float(…)包装:

float("{:.2f}".format(13.949999999999999))

注意2:用float()换行不会改变任何内容:

>>> x = 13.949999999999999999
>>> x
13.95
>>> g = float("{:.2f}".format(x))
>>> g
13.95
>>> x == g
True
>>> h = round(x, 2)
>>> h
13.95
>>> x == h
True

正如Matt所指出的,Python 3.6提供了f字符串,它们也可以使用嵌套参数:

value = 2.34558
precision = 2
width = 4

print(f'result: {value:{width}.{precision}f}')

显示结果:2.35

如果您想处理金钱,请使用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