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

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

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


当前回答

要将一个数字舍入为一个分辨率,最好的方法是以下方法,该方法可以适用于任何分辨率(两个小数或甚至其他步长为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

其他回答

简单的解决方案在这里

value = 5.34343
rounded_value = round(value, 2) # 5.34
from decimal import Decimal


def round_float(v, ndigits=2, rt_str=False):
    d = Decimal(v)
    v_str = ("{0:.%sf}" % ndigits).format(round(d, ndigits))
    if rt_str:
        return v_str
    return Decimal(v_str)

结果:

Python 3.6.1 (default, Dec 11 2018, 17:41:10)
>>> round_float(3.1415926)
Decimal('3.14')
>>> round_float(3.1445926)
Decimal('3.14')
>>> round_float(3.1455926)
Decimal('3.15')
>>> round_float(3.1455926, rt_str=True)
'3.15'
>>> str(round_float(3.1455926))
'3.15'

Python教程有一个名为“浮点算术:问题和限制”的附录。阅读它。它解释了正在发生的事情以及为什么Python做得最好。它甚至有一个与您的示例相匹配的示例。让我引用一点:

>>> 0.10.10000000000000001您可能会尝试使用round()函数将其切回单个您期望的数字。但这并不意味着差异:>>>圆形(0.1,1)0.10000000000000001问题是二进制文件为“0.1”存储的浮点值已经是最好的二进制了接近1/10,因此尝试再圆一次也不能让它变得更好:它已经很好了。另一个结果是,由于0.1不是十分之一,加十0.1的值可能不会产生精确的结果1.0,或者:>>>总和=0.0>>>对于范围(10)中的i:…总和+=0.1...>>>总和0.99999999999999989

解决问题的另一种方法是使用十进制模块。

Use:

float_number = 12.234325335563
round(float_number, 2)

这将返回;

12.23

说明:

round函数接受两个参数;要舍入的数字和要返回的小数位数。这里我返回了两位小数。

对于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文档中的字符串格式链接。

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

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