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

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

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


当前回答

打印百分比的单行函数:

k——分子

n-分母

“%.2f”-表示需要2位小数的精度

*100-将数字从小数转换为百分比

   percentage = lambda k, n: '%.2f' % (k/n*100)

   - equivalent to-

   def percentage(k,n):
       return '%.2f' % (k/n*100)

百分比(1,3)

输出->“33.33”

其他回答

在Python中,可以使用格式运算符将值舍入到两位小数:

print(format(14.4499923, '.2f')) // The output is 14.45

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

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

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

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'

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

下面是使用format函数的简单解决方案。

float(format(num, '.2f'))

注意:我们将数字转换为浮点数,因为format方法返回字符串。