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

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

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


当前回答

使用Decimal对象和round()方法的组合。

Python 3.7.3
>>> from decimal import Decimal
>>> d1 = Decimal (13.949999999999999) # define a Decimal
>>> d1 
Decimal('13.949999999999999289457264239899814128875732421875')
>>> d2 = round(d1, 2) # round to 2 decimals
>>> d2
Decimal('13.95')

其他回答

这很简单,比如:

使用十进制模块进行快速正确舍入的十进制浮点运算:d=十进制(10000000.0000009)为了实现舍入:d.quantite(十进制('0.01'))将产生十进制('10000000.00')使上述干燥:def round_decimal(数字,指数='0.01'):decimal_value=十进制(数字)return decimal_value.g量化(十进制(指数))或定义round_decimal(数字,小数位数=2):decimal_value=十进制(数字)return decimal_value.g量化(十进制(10)**-decimal_places)

PS:对其他人的批评:格式不是舍入。

对于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文档中的字符串格式链接。

关于选项一的更多信息,这个链接就足够了,并提供了各种标志的信息。

引用:将浮点数转换为特定精度,然后复制为字符串

我们有多种选择:

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

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

您可以修改输出格式:

>>> a = 13.95
>>> a
13.949999999999999
>>> print "%.2f" % a
13.95