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

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

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


当前回答

使用如下lambda函数:

arred = lambda x,n : x*(10**n)//1/(10**n)

这样你就可以:

arred(3.141591657, 2)

然后得到

3.14

其他回答

它正按照您的指示执行,并且工作正常。阅读更多关于浮点混淆的内容,并尝试使用十进制对象。

下面是使用format函数的简单解决方案。

float(format(num, '.2f'))

注意:我们将数字转换为浮点数,因为format方法返回字符串。

请尝试以下代码:

>>> a = 0.99334
>>> a = int((a * 100) + 0.5) / 100.0 # Adding 0.5 rounds it up
>>> print a
0.99
lambda x, n:int(x*10^n + 0.5)/10^n

他为我工作了很多年,精通多种语言。

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