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

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

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


当前回答

简单的解决方案在这里

value = 5.34343
rounded_value = round(value, 2) # 5.34

其他回答

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

您可以执行以下操作:

"{:.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

请尝试以下代码:

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

让我举一个Python 3.6的f-string/模板字符串格式的例子,我认为它非常整洁:

>>> f'{a:.2f}'

它也适用于较长的示例,使用运算符,不需要括号:

>>> print(f'Completed in {time.time() - start:.2f}s')

使用如下lambda函数:

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

这样你就可以:

arred(3.141591657, 2)

然后得到

3.14

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

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