我希望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')

其他回答

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

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

为了修复Python和JavaScript等类型动态语言中的浮点,我使用了这种技术

# For example:
a = 70000
b = 0.14
c = a * b

print c # Prints 980.0000000002
# Try to fix
c = int(c * 10000)/100000
print c # Prints 980

您还可以按以下方式使用Decimal:

from decimal import *
getcontext().prec = 6
Decimal(1) / Decimal(7)
# Results in 6 precision -> Decimal('0.142857')

getcontext().prec = 28
Decimal(1) / Decimal(7)
# Results in 28 precision -> Decimal('0.1428571428571428571428571429')

大多数数字不能用浮点数精确表示。如果你想舍入这个数字,因为这是你的数学公式或算法所要求的,那么你想使用舍入。如果您只想将显示限制为某一精度,那么甚至不要使用舍入,只需将其格式化为字符串即可。(如果您想用其他舍入方法显示,并且有吨,则需要混合使用这两种方法。)

>>> "%.2f" % 3.14159
'3.14'
>>> "%.2f" % 13.9499999
'13.95'

最后,也许最重要的是,如果你想要精确的数学,那么你根本不需要浮点数。通常的例子是处理货币,并将“美分”存储为整数。

对于原始Python:

对于浮点到字符串转换的2个小数点:

a = 13.949999999999999
format(a, '.2f')

对于浮点到浮点转换的2个小数点:

a = 13.949999999999999
round(float(a), 2)
or
float(format(a, '.2f'))

要计算,我使用函数截断值也许对你有帮助

import math


def truncate(number, digits) -> float:
    stepper = pow(10.0, digits)
    return math.trunc(stepper * number) / stepper


print(truncate((0.1 + 0.2), 2))