How to format a floating number to fixed width in Python

后端 未结 8 1068
长发绾君心
长发绾君心 2020-11-22 10:26

How do I format a floating number to a fixed width with the following requirements:

  1. Leading zero if n < 1
  2. Add trailing decimal zero(s) to fill up f
相关标签:
8条回答
  • 2020-11-22 10:47
    for x in numbers:
        print "{:10.4f}".format(x)
    

    prints

       23.2300
        0.1233
        1.0000
        4.2230
     9887.2000
    

    The format specifier inside the curly braces follows the Python format string syntax. Specifically, in this case, it consists of the following parts:

    • The empty string before the colon means "take the next provided argument to format()" – in this case the x as the only argument.
    • The 10.4f part after the colon is the format specification.
    • The f denotes fixed-point notation.
    • The 10 is the total width of the field being printed, lefted-padded by spaces.
    • The 4 is the number of digits after the decimal point.
    0 讨论(0)
  • 2020-11-22 10:53

    In python3 the following works:

    >>> v=10.4
    >>> print('% 6.2f' % v)
      10.40
    >>> print('% 12.1f' % v)
            10.4
    >>> print('%012.1f' % v)
    0000000010.4
    
    0 讨论(0)
  • 2020-11-22 10:59

    See Python 3.x format string syntax:

    IDLE 3.5.1   
    numbers = ['23.23', '.1233', '1', '4.223', '9887.2']
    
    for x in numbers:  
        print('{0: >#016.4f}'. format(float(x)))  
    
         23.2300
          0.1233
          1.0000
          4.2230
       9887.2000
    
    0 讨论(0)
  • 2020-11-22 11:01

    It has been a few years since this was answered, but as of Python 3.6 (PEP498) you could use the new f-strings:

    numbers = [23.23, 0.123334987, 1, 4.223, 9887.2]
    
    for number in numbers:
        print(f'{number:9.4f}')
    

    Prints:

      23.2300
       0.1233
       1.0000
       4.2230
    9887.2000
    
    0 讨论(0)
  • 2020-11-22 11:05

    In Python 3.

    GPA = 2.5
    print(" %6.1f " % GPA)
    

    6.1f means after the dots 1 digits show if you print 2 digits after the dots you should only %6.2f such that %6.3f 3 digits print after the point.

    0 讨论(0)
  • 2020-11-22 11:06

    I needed something similar for arrays. That helped me

    some_array_rounded=np.around(some_array, 5)
    
    0 讨论(0)
提交回复
热议问题