Rounding to two decimal places in Python 2.7?

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

    When working with pennies/integers. You will run into a problem with 115 (as in $1.15) and other numbers.

    I had a function that would convert an Integer to a Float.

    ...
    return float(115 * 0.01)
    

    That worked most of the time but sometimes it would return something like 1.1500000000000001.

    So I changed my function to return like this...

    ...
    return float(format(115 * 0.01, '.2f'))
    

    and that will return 1.15. Not '1.15' or 1.1500000000000001 (returns a float, not a string)

    I'm mostly posting this so I can remember what I did in this scenario since this is the first result in google.

提交回复
热议问题