Display a float with two decimal places in Python

前端 未结 11 1935
我在风中等你
我在风中等你 2020-11-22 14:36

I have a function taking float arguments (generally integers or decimals with one significant digit), and I need to output the values in a string with two decimal places (5

相关标签:
11条回答
  • 2020-11-22 14:47

    String formatting:

    print "%.2f" % 5
    
    0 讨论(0)
  • 2020-11-22 14:56

    If you want to get a floating point value with two decimal places limited at the time of calling input,

    Check this out ~

    a = eval(format(float(input()), '.2f'))   # if u feed 3.1415 for 'a'.
    print(a)                                  # output 3.14 will be printed.
    
    0 讨论(0)
  • 2020-11-22 14:59

    Shortest Python 3 syntax:

    n = 5
    print(f'{n:.2f}')
    
    0 讨论(0)
  • 2020-11-22 15:00

    Using Python 3 syntax:

    print('%.2f' % number)
    
    0 讨论(0)
  • Since this post might be here for a while, lets also point out python 3 syntax:

    "{:.2f}".format(5)
    
    0 讨论(0)
提交回复
热议问题