Rounding to two decimal places in Python 2.7?

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

    A rather simple workaround is to convert the float into string first, the select the substring of the first four numbers, finally convert the substring back to float. For example:

    >>> out1 = 1.2345
    >>> out1 = float(str(out1)[0:4])
    >>> out1
    

    May not be super efficient but simple and works :)

    0 讨论(0)
  • 2020-12-01 00:02

    When we use the round() function, it will not give correct values.

    you can check it using, round (2.735) and round(2.725)

    please use

    import math
    num = input('Enter a number')
    print(math.ceil(num*100)/100)
    
    0 讨论(0)
  • 2020-12-01 00:11

    You can use str.format(), too:

    >>> print "financial return of outcome 1 = {:.2f}".format(1.23456)
    financial return of outcome 1 = 1.23
    
    0 讨论(0)
提交回复
热议问题