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

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

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


当前回答

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

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

其他回答

我们有多种选择:

选项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 3.6的f-string/模板字符串格式的例子,我认为它非常整洁:

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

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

>>> print(f'Completed in {time.time() - start:.2f}s')
orig_float = 232569 / 16000.0

14.5355625

short_float = float("{:.2f}".format(orig_float)) 

14.54

只需使用此函数并将字节作为输入传递给它:

def getSize(bytes):
    kb = round(bytes/1024, 4)
    mb = round(kb/1024, 4)
    gb = round(mb/1024, 4)
    if(gb > 1):
        return str(gb) + " GB"
    elif(mb > 1):
        return str(mb) + " MB"
    else:
        return str(kb) + " KB"

这是将数据大小从字节动态转换为KB、MB或GB的最简单方法。