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

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

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


当前回答

正如Matt所指出的,Python 3.6提供了f字符串,它们也可以使用嵌套参数:

value = 2.34558
precision = 2
width = 4

print(f'result: {value:{width}.{precision}f}')

显示结果:2.35

其他回答

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

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

orig_float = 232569 / 16000.0

14.5355625

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

14.54

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

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

要将一个数字舍入为一个分辨率,最好的方法是以下方法,该方法可以适用于任何分辨率(两个小数或甚至其他步长为0.01):

>>> import numpy as np
>>> value = 13.949999999999999
>>> resolution = 0.01
>>> newValue = int(np.round(value/resolution))*resolution
>>> print newValue
13.95

>>> resolution = 0.5
>>> newValue = int(np.round(value/resolution))*resolution
>>> print newValue
14.0

你遇到了一个关于浮点数的老问题,不是所有的数字都能精确表示。命令行只是显示内存中的完整浮点形式。

对于浮点表示法,舍入版本是相同的数字。由于计算机是二进制的,它们将浮点数存储为整数,然后将其除以2的幂,因此13.95将以类似于125650429603636838/(2**53)的方式表示。

双精度数字的精度为53位(16位),常规浮点数的精度为24位(8位)。Python中的浮点类型使用双精度来存储值。

例如

>>> 125650429603636838/(2**53)
13.949999999999999

>>> 234042163/(2**24)
13.949999988079071

>>> a = 13.946
>>> print(a)
13.946
>>> print("%.2f" % a)
13.95
>>> round(a,2)
13.949999999999999
>>> print("%.2f" % round(a, 2))
13.95
>>> print("{:.2f}".format(a))
13.95
>>> print("{:.2f}".format(round(a, 2)))
13.95
>>> print("{:.15f}".format(round(a, 2)))
13.949999999999999

如果您只在小数点后两位(例如显示货币值),那么您有两个更好的选择:

使用整数并以美分而非美元存储值,然后除以100转换为美元。或者使用小数等固定点数。