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

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

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


当前回答

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

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的最简单方法。

其他回答

请尝试以下代码:

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

我们有多种选择:

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

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

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

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

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

简单的解决方案在这里

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

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

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

float = str(float)[:5]

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

希望这有帮助!