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

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

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


当前回答

在Python中,可以使用格式运算符将值舍入到两位小数:

print(format(14.4499923, '.2f')) // The output is 14.45

其他回答

Use

print"{:.2f}".format(a)

而不是

print"{0:.2f}".format(a)

因为后者在尝试输出多个变量时可能会导致输出错误(请参见注释)。

在Python中,可以使用格式运算符将值舍入到两位小数:

print(format(14.4499923, '.2f')) // The output is 14.45

我们有多种选择:

选项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)

我使用的方法是字符串切片。它相对快速和简单。

首先,将浮点数转换为字符串,然后选择您希望的长度。

float = str(float)[:5]

在上面的单行中,我们将值转换为字符串,然后将字符串仅保留为其前四位数字或字符(包括)。

希望这有帮助!

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