515

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

14 Answers 14

727
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.
Sign up to request clarification or add additional context in comments.

17 Comments

So I understand that the 4f represents limiting the decimals to 4 (with trailing zeros), but what does the 10 mean? Does that mean this formatting won't work with integers greater than 9999999999 (ten 9's)? Just curious.
10.4 means a width of 10 characters and a precision of 4 decimal places.
@hobbes3: 10 is the minimum field width, i.e. the minimum length of the printed string. Numbers are by default right-aligned and padded with spaces -- see the documentation for more details.
For Pythons prior to 2.7: ("%0.4f" % x).rjust(10)
@StevenRumbalski: Or simply "%10.4f" % x. In Python 2.6, you can also use "{0:10.4f}".format(x).
|
256

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

2 Comments

Note that the width also includes dot character. So if you specify 9 to be width, 1 will be used for printing the dot, the other 8 will be for printing digits and spaces.
A very large number may still result in a string longer than otherwise, so this isn't truly "fixed width" (depending on your interpretation of the term).
52

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

2 Comments

This has changed in the last 4 years, now % formatting is the oldest method of formatting. For several reasons using str.format or f-strings is preferred over %. Previously when it was only str.format, people had some reasons but f-strings fixed that hole. format mini-language docs, str.format examples from docs and f-string literals examples in docs
The above comment is true in general. However, when debugging the lzay formatting is still preferred, see logging-fstring-interpolation / W1203.
21

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 (including spaces), 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

3 Comments

Is there any reason why "print(f"{number:5f}")" doesn't work as expected? It outputs 9 symbols ("12.340000"). Looks like 9 is the smallest width? But why? At the same time, adding the number of digits after decimal separator (5.2f) prints a string of 5 symbols as expected.
@Roman According to the documentation for the f type, "With no precision given, uses a precision of 6 digits after the decimal point for float,". So print(f"number:99f") will print a number that is at least 99 spaces wide, defaulting to six decimal places, since no precision was given, only width.
+1 for variables. I can see the use case when dealing with larger applications that might need a uniform number format that a user can specify from a settings menu.
14

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.

Comments

13

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

Comments

12

This will print 76.66:

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

Comments

4

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.

Comments

2

Here's a summary of formatting floats using f-strings, with padding and alignment, and with/without the float 'f' indicator.

>>> f"{0.12}"
'0.12'
>>> f"{0.12:.4}"
'0.12'
>>> f"{0.12:.4f}"
'0.1200'

Fixed width (with and without padding)

>>> f"{0.12:8.4}"
'    0.12'
>>> f"{0.12:8.4f}"
'  0.1200'
>>> f"{0.12:08.4}"
'00000.12'
>>> f"{0.12:08.4f}"
'000.1200'

Left alignment

>>> f"{0.12:<8.4}"
'0.12    '
>>> f"{0.12:<8.4f}"
'0.1200  '
>>> f"{0.12:<08.4}"
'0.120000'
>>> f"{0.12:<08.4f}"
'0.120000'

Center alignment

>>> f"{0.12:^8.4}"
'  0.12  '
>>> f"{0.12:^8.4f}"
' 0.1200 '
>>> f"{0.12:^08.4}"
'000.1200'
>>> f"{0.12:^08.4f}"
'00.12000'

Comments

1

I needed something similar for arrays. That helped me

some_array_rounded=np.around(some_array, 5)

Comments

1

Note that most answers here can return a string longer than the indicated width, if the number is still very large.

If you absolutely need the resulting string to be exactly a certain number of characters, because e.g. you want to display it in a fixed-width font in a table or other context where the number of characters is critical, I don't think there is something built-in for this. A custom function which switches over to scientific notation to save space is possible, i.e. something like the following:

def fpstr(n, width, sign=''):
    n = float(n)
    attempts = []
    def v(s):
        if len(s) != width:
            return
        try:
            float(s)
        except Exception:
            return
        attempts.append(s)

    for w in reversed(range(width)):
        v("{:{}0.0{}f}".format(n, sign, w))

    for w in reversed(range(width)):
        v("{:{}0.0{}g}".format(n, sign, w))

    for w in reversed(range(width)):
        v("{:{}{}g}".format(n, sign, w).rjust(width))

    for w in reversed(range(width)):
        v("{:{}.{}e}".format(n, sign, w).rjust(width))

    if not attempts:
        return "#" * width

    best_attempt = attempts[0]
    for attempt in attempts[1:]:
        if abs(n - float(attempt)) < abs(n - float(best_attempt)):
            best_attempt = attempt
    return best_attempt

(This is a draft so leaving this as a community wiki to allow future improvement.)

Comments

1

(Disclosure: I am the owner of the repo)

PyFi is a library that helps converting fixed-point to floating-point and vice-versa. Here is an example:

PYTHON FIXED POINT CONVERTER
Configuration:
-Type of conversion: Floating to fixed point
-Signedness: Signed
-Total bits: 32
-Fractional bits: 31
WARNING: 1.0 can not be represented, 0.99999999977 will be used instead ( index: 0 )
Converted values:
-Dec (Input): 0.99999999977,-0.50000000000
-Hex (Output): 0x7fffffff,0xc0000000
-Bin (Output): 0b01111111111111111111111111111111,0b11000000000000000000000000000000

Comments

-1

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.

Comments

-1

totalSales=1000

print ("\rTotal Sales Amount is :"+ f"{float(totalSales):,.2f}")

output: Total Sales Amount is :1,000.00

:, formats the number with commas as thousands separators.

.2f ensures the number is formatted with two digits after the decimal point.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.