我希望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”

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 2.7中:

a = 13.949999999999999
output = float("%0.2f"%a)
print output

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

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

我看到的答案对浮点数(52.15)不起作用。经过一些测试,我使用的解决方案是:

import decimal
        
def value_to_decimal(value, decimal_places):
    decimal.getcontext().rounding = decimal.ROUND_HALF_UP  # define rounding method
    return decimal.Decimal(str(float(value))).quantize(decimal.Decimal('1e-{}'.format(decimal_places)))

(将“value”转换为float和string非常重要,这样一来,“value”可以是float、decimal、integer或string类型!)

希望这对任何人都有帮助。