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

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

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


当前回答

对于原始Python:

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

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

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

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

其他回答

对于原始Python:

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

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

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

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

内置round()在Python 2.7或更高版本中运行良好。

例子:

>>> round(14.22222223, 2)
14.22

查看文档。

对于Python<3(例如2.6或2.7),有两种方法可以实现。

# Option one 
older_method_string = "%.9f" % numvar

# Option two (note ':' before the '.9f')
newer_method_string = "{:.9f}".format(numvar)

但请注意,对于3以上的Python版本(例如3.2或3.3),首选选项二。

有关选项2的更多信息,我建议使用Python文档中的字符串格式链接。

关于选项一的更多信息,这个链接就足够了,并提供了各种标志的信息。

引用:将浮点数转换为特定精度,然后复制为字符串

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

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

使用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')