How to format a floating number to fixed width in Python

PythonStringNumbersNumber Formatting

Python Problem Overview


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 fixed width
  3. Truncate decimal digits past fixed width
  4. Align all decimal points

For example:

% formatter something like '{:06}'
numbers = [23.23, 0.123334987, 1, 4.223, 9887.2]

for number in numbers:
    print formatter.format(number)

The output would be like

  23.2300
   0.1233
   1.0000
   4.2230
9887.2000

Python Solutions


Solution 1 - Python

numbers = [23.23, 0.1233, 1.0, 4.223, 9887.2]                                                                                                                                                   
                                                                                                                                                                                                
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.

Solution 2 - Python

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

Solution 3 - Python

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

Solution 4 - Python

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

Solution 5 - Python

You can also left pad with zeros. For example if you want number to have 9 characters length, left padded with zeros use:

print('{:09.3f}'.format(number))

Thus, if number = 4.656, the output is: 00004.656

For your example the output will look like this:

numbers  = [23.2300, 0.1233, 1.0000, 4.2230, 9887.2000]
for x in numbers: 
    print('{:010.4f}'.format(x))

prints:

00023.2300
00000.1233
00001.0000
00004.2230
09887.2000

One example where this may be useful is when you want to properly list filenames in alphabetical order. I noticed in some linux systems, the number is: 1,10,11,..2,20,21,...

Thus if you want to enforce the necessary numeric order in filenames, you need to left pad with the appropriate number of zeros.

Solution 6 - Python

This will print 76.66:

print("Number: ", f"{76.663254: .2f}")

Solution 7 - Python

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.

Solution 8 - Python

I needed something similar for arrays. That helped me

some_array_rounded=np.around(some_array, 5)

Solution 9 - Python

Using f-string literals:

>>> number = 12.34
>>> print(f"{number}")
12.34
>>> print(f"{number:10f}")
 12.340000
>>> print(f"{number:10.4f}")
   12.3400

The 10.4f after the colon : is the format specification, with 10 being the width in characters of the whole number, and the second number 4 being the number of decimal places, and the f standing for floating-point number.

It's also possible to use variables instead of hard-coding the width and the number of decimal places:

>>> number = 12.34
>>> width = 10
>>> decimals = 4
>>> print(f"{number:{width}.{decimals}f}")
   12.3400

Solution 10 - Python

I tried all the options like

  1. pd.options.display.float_format = '{:.4f}'.format
  2. pd.set_option('display.float_format', str)
  3. pd.set_option('display.float_format', lambda x: f'%.{len(str(x%1))-2}f' % x)
  4. pd.set_option('display.float_format', lambda x: '%.3f' % x)

but nothing worked for me.

so while assigning the variable/value (var1) to a variable (say num1) I used round(val,5) like

num1 = round(var1,5)

This is a crude method as you have to use this round function in each assignment. But this ensures you control on how it happens and get what you want.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionhobbes3View Question on Stackoverflow
Solution 1 - PythonSven MarnachView Answer on Stackoverflow
Solution 2 - PythonartomasonView Answer on Stackoverflow
Solution 3 - PythonScott RobertsView Answer on Stackoverflow
Solution 4 - PythonreadyleaderView Answer on Stackoverflow
Solution 5 - PythonelcymonView Answer on Stackoverflow
Solution 6 - PythonMattView Answer on Stackoverflow
Solution 7 - PythonUsman ZiaView Answer on Stackoverflow
Solution 8 - PythonAnton View Answer on Stackoverflow
Solution 9 - PythonFlimmView Answer on Stackoverflow
Solution 10 - PythonShekhar MahajanView Answer on Stackoverflow