Rounding to two decimal places in Python 2.7?

后端 未结 9 2482
一个人的身影
一个人的身影 2020-11-30 23:34

Using Python 2.7 how do I round my numbers to two decimal places rather than the 10 or so it gives?

print \"financial return of outcome 1 =\",\"$\"+str(out1)         


        
9条回答
  •  渐次进展
    2020-11-30 23:51

    Since you're talking about financial figures, you DO NOT WANT to use floating-point arithmetic. You're better off using Decimal.

    >>> from decimal import Decimal
    >>> Decimal("33.505")
    Decimal('33.505')
    

    Text output formatting with new-style format() (defaults to half-even rounding):

    >>> print("financial return of outcome 1 = {:.2f}".format(Decimal("33.505")))
    financial return of outcome 1 = 33.50
    >>> print("financial return of outcome 1 = {:.2f}".format(Decimal("33.515")))
    financial return of outcome 1 = 33.52
    

    See the differences in rounding due to floating-point imprecision:

    >>> round(33.505, 2)
    33.51
    >>> round(Decimal("33.505"), 2)  # This converts back to float (wrong)
    33.51
    >>> Decimal(33.505)  # Don't init Decimal from floating-point
    Decimal('33.50500000000000255795384873636066913604736328125')
    

    Proper way to round financial values:

    >>> Decimal("33.505").quantize(Decimal("0.01"))  # Half-even rounding by default
    Decimal('33.50')
    

    It is also common to have other types of rounding in different transactions:

    >>> import decimal
    >>> Decimal("33.505").quantize(Decimal("0.01"), decimal.ROUND_HALF_DOWN)
    Decimal('33.50')
    >>> Decimal("33.505").quantize(Decimal("0.01"), decimal.ROUND_HALF_UP)
    Decimal('33.51')
    

    Remember that if you're simulating return outcome, you possibly will have to round at each interest period, since you can't pay/receive cent fractions, nor receive interest over cent fractions. For simulations it's pretty common to just use floating-point due to inherent uncertainties, but if doing so, always remember that the error is there. As such, even fixed-interest investments might differ a bit in returns because of this.

提交回复
热议问题