Rounding to two decimal places in Python 2.7?

后端 未结 9 2506
一个人的身影
一个人的身影 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:52

    Use the built-in function round():

    >>> round(1.2345,2)
    1.23
    >>> round(1.5145,2)
    1.51
    >>> round(1.679,2)
    1.68
    

    Or built-in function format():

    >>> format(1.2345, '.2f')
    '1.23'
    >>> format(1.679, '.2f')
    '1.68'
    

    Or new style string formatting:

    >>> "{:.2f}".format(1.2345)
    '1.23
    >>> "{:.2f}".format(1.679)
    '1.68'
    

    Or old style string formatting:

    >>> "%.2f" % (1.679)
    '1.68'
    

    help on round:

    >>> print round.__doc__
    round(number[, ndigits]) -> floating point number
    
    Round a number to a given precision in decimal digits (default 0 digits).
    This always returns a floating point number.  Precision may be negative.
    

提交回复
热议问题