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.
Answer from Sven Marnach on Stack Overflow
🌐
GeeksforGeeks
geeksforgeeks.org › python › format-a-number-width-in-python
Format a Number Width in Python - GeeksforGeeks
July 23, 2025 - If you notice the second line of the output, you can see that the right most number is 5 instead of 4. Our number at the fourth decimal place was incremented by 1 because if the value at the position from where the numbers have to be dropped is greater than 5, then the right most number in the output will be incremented by 1, else it remains the same. ... my_float = 4.163476 print(my_float) # formatting a float to fixed width of 7 with 4 digits after the decimal print(f"{my_float:7.4f}")
Discussions

string - Python: How do I format numbers for a fixed width? - Stack Overflow
let's say numbers = [ 0.7653, 10.2, 100.2325, 500.9874 ] I'd like to output the numbers with a fixed width by varying the number of decimal places to get an output like this: 0.7653 10.200 100.2... More on stackoverflow.com
🌐 stackoverflow.com
April 13, 2017
Python format Integer into fixed length strings - Stack Overflow
I want to generate a string based on an int along with zeros. And the length should always be of 5 not more then that nor less. For example: Consider a Integer: 1 Formatted String : 00001 Consid... More on stackoverflow.com
🌐 stackoverflow.com
python - Fixed-width number formatting - Stack Overflow
Note: This will truncate the result, not round it as formatting would. ... Sign up to request clarification or add additional context in comments. ... This will give an incorrect answer as it truncates the number rather than rounding. More on stackoverflow.com
🌐 stackoverflow.com
string - How to format a floating number to maximum fixed width in Python - Stack Overflow
I am writing an input file to a program with roots in the 60s, and it reads data from fixed-width data fields on text files. The format is: field width 8 characters floating point numbers must cont... More on stackoverflow.com
🌐 stackoverflow.com
July 10, 2019
🌐
Bobby Hadz
bobbyhadz.com › blog › python-format-number-fixed-width
Format a Number to a fixed Width in Python | bobbyhadz
Use a formatted string literal to format a number to a fixed width, e.g. `result = f'{my_int:03d}'`.
🌐
LabEx
labex.io › tutorials › python-how-to-convert-numbers-to-fixed-width-464394
How to convert numbers to fixed width | LabEx
import timeit ## Comparing formatting methods def percent_format(): return "d" % 42 def format_method(): return "{:05d}".format(42) def fstring_method(): return f"{42:05d}" ## Benchmark formatting performance print("Percent Format:", timeit.timeit(percent_format, number=10000)) print("Format Method:", timeit.timeit(format_method, number=10000)) print("F-String Method:", timeit.timeit(fstring_method, number=10000)) ... By mastering fixed-width number conversion in Python, developers can enhance their data presentation skills, create more readable output, and implement precise formatting techniques.
🌐
GitHub
github.com › bobbyhadz › python-format-number-fixed-width › blob › main › main.py
python-format-number-fixed-width/main.py at main · bobbyhadz/python-format-number-fixed-width
A repository for an article at https://bobbyhadz.com/blog/python-format-number-fixed-width - bobbyhadz/python-format-number-fixed-width
Author: bobbyhadz
🌐
Delft Stack
delftstack.com › home › howto › python › python format float to string
How to Format a Floating Number to String in Python | Delft Stack
February 2, 2024 - Formatting floating-point numbers to a fixed width using format specification and the format() method in Python involves employing the format() function with a specific format specification.
Find elsewhere
Top answer
1 of 2
20

Combining two str.format / format calls:

numbers = [ 0.7653, 10.2, 100.2325, 500.9874 ]
>>> for n in numbers:
...     print('{:.6s}'.format('{:0.4f}'.format(n)))
...     #  OR format(format(n, '0.4f'), '.6s')
...
0.7653
10.200
100.23
500.98

or % operators:

>>> for n in numbers:
...     print('%.6s' % ('%.4f' % n))
...
0.7653
10.200
100.23
500.98

Alternatively, you can use slicing:

>>> for n in numbers:
...     print(('%.4f' % n)[:6])
...
0.7653
10.200
100.23
500.98
2 of 2
5

Unfortunately, there is no out-of-box solution for this problem. Moreover, the solution with string slicing does not adequately handles rounding as well as overflows.

Therefore, it seems that one has to write an own function like this:

def to_fixed_width(n, max_width, allow_overflow = True, do_round = True):
    if do_round:
        for i in range(max_width - 2, -1, -1):
            str0 = '{:.{}f}'.format(n, i)
            if len(str0) <= max_width:
                break
    else:
        str0 = '{:.42f}'.format(n)
        int_part_len = str0.index('.')
        if int_part_len <= max_width - 2:
            str0 = str0[:max_width]
        else:
            str0 = str0[:int_part_len]
    if (not allow_overflow) and (len(str0) > max_width):
        raise OverflowError("Impossible to represent in fixed-width non-scientific format")
    return str0

The resulting behavior:

>>> to_fixed_width(0.7653, 6)
'0.7653'
>>> to_fixed_width(10.2, 6)
'10.200'
>>> to_fixed_width(100.2325, 6)
'100.23'
>>> to_fixed_width(500.9874, 6)
'500.99'
>>> to_fixed_width(500.9874, 6, do_round = False)
'500.98'

More examples:

>>> to_fixed_width(-0.3, 6)
'-0.300'
>>> to_fixed_width(0.000001, 6)
'0.0000'
>>> to_fixed_width(999.99, 6)
'999.99'
>>> to_fixed_width(999.999, 6)
'1000.0'
>>> to_fixed_width(1000.4499, 6)
'1000.4'
>>> to_fixed_width(1000.4499, 6, do_round = False)
'1000.4'
>>> to_fixed_width(12345.6, 6)
'12346'
>>> to_fixed_width(1234567, 6)
'1234567'
>>> to_fixed_width(1234567, 6, allow_overflow = False)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 15, in to_fixed_width
OverflowError: Impossible to represent in fixed-width non-scientific format
>>> to_fixed_width(float('nan'), 6)
'nan'
🌐
Tutorial Reference
tutorialreference.com › python › examples › faq › python-how-to-format-number-to-fixed-width
How to Format Numbers to Fixed Width in Python | Tutorial Reference
Formatted string literals (f-strings) provide a concise way to format numbers to a fixed width. To left-pad a number with leading zeros, use the format specifier 0 followed by the desired width and the type specifier d for integer:
Author: bobbyhadz
🌐
Python Forum
python-forum.io › thread-18651.html
fixed width numbers
is there an easy way to output numbers in a simple print() call in a fixed width? for cases with leading zeros i have been doing:print(str(number+1000000))but now i want to have leading spaces. do i n
Top answer
1 of 4
3

I simply took the answer by @Harvey251 but split into test part and the part we need in production.

Usage would be:

# save the code at the end as formatfloat.py and then
import formatfloat

# do this first
width = 8
ff8 = formatfloat.FormatFloat(width)

# now use ff8 whenever you need
print(ff8(12345678901234))

And here is the solution. Save the code as formatfloat.py and import it to use FlotFormat class. As I said below, loop part of calculation better be moved to init part of the FormatFlot class.

import unittest

class FormatFloat:
    def __init__(self, width = 8):
        self.width = width
        self.maxnum = int('9'*(width - 1))  # 9999999
        self.minnum = -int('9'*(width - 2)) # -999999

    def __call__(self, x):

        # for small numbers
        # if -999,999 < given < 9,999,999:
        if x > self.minnum and x < self.maxnum:

            # o = f'{x:7}'
            o = f'{x:{self.width - 1}}'

            # converting int to float without adding zero
            if '.' not in o:
                o += '.'

            # float longer than 8 will need rounding to fit width
            elif len(o) > self.width:
                # output = str(round(x, 7 - str(x).index(".")))
                o = str(round(x, self.width-1 - str(x).index('.')))

        else:

            # for exponents
            # added a loop for super large numbers or negative as "-" is another char
            # Added max(max_char, 5) to account for max length of less 
            #     than 5, was having too much fun
            # TODO can i come up with a threshold value for these up front, 
            #     so that i dont have to do this calc for every value??
            for n in range(max(self.width, 5) - 5, 0, -1):
                fill = f'.{n}e'
                o = f'{x:{fill}}'.replace('+0', '+')

                # if all good stop looping
                if len(o) == self.width:
                    break
            else:
                raise ValueError(f"Number is too large to fit in {self.width} characters", x)
        return o


class TestFormatFloat(unittest.TestCase):
    def test_all(self):
        test = ( 
            ("1234567.", 1234567), 
            ("-123456.", -123456), 
            ("1.23e+13", 12345678901234), 
            ("123.4567", 123.4567), 
            ("123.4568", 123.45678), 
            ("1.234568", 1.2345678), 
            ("0.123457", 0.12345678), 
            ("   1234.", 1234), 
            ("1.235e+7", 12345678), 
            ("-1.23e+6", -1234567),
            )

        width = 8
        ff8 = FormatFloat(width)

        for expected, given in test:
            output = ff8(given)
            self.assertEqual(len(output), width, msg=output)
            self.assertEqual(output, expected, msg=given)

if __name__ == '__main__':
    unittest.main()
2 of 4
3

I've made a slight addition to yosukesabai's contribution to account for the rare case where rounding will make the width of the string 7 characters instead of 8!

class FormatFloat:
def __init__(self, width = 8):
    self.width = width
    self.maxnum = int('9'*(width - 1))  # 9999999
    self.minnum = -int('9'*(width - 2)) # -999999

def __call__(self, x):

    # for small numbers
    # if -999,999 < given < 9,999,999:
    if x > self.minnum and x < self.maxnum:

        # o = f'{x:7}'
        o = f'{x:{self.width - 1}}'

        # converting int to float without adding zero
        if '.' not in o:
            o += '.'

        # float longer than 8 will need rounding to fit width
        elif len(o) > self.width:
            # output = str(round(x, 7 - str(x).index(".")))
            o = str(round(x, self.width - 1 - str(x).index('.')))
            if len(o) < self.width:
                o+=(self.width-len(o))*'0'

    else:

        # for exponents
        # added a loop for super large numbers or negative as "-" is another char
        # Added max(max_char, 5) to account for max length of less 
        #     than 5, was having too much fun
        # TODO can i come up with a threshold value for these up front, 
        #     so that i dont have to do this calc for every value??
        for n in range(max(self.width, 5) - 5, 0, -1):
            fill = f'.{n}e'
            o = f'{x:{fill}}'.replace('+0', '+')

            # if all good stop looping
            if len(o) == self.width:
                break
        else:
            raise ValueError(f"Number is too large to fit in {self.width} characters", x)
    return o
🌐
sqlpey
sqlpey.com › python › solved-how-to-format-floating-numbers-to-fixed-width-in-python
Solved: How to Format Floating Numbers to Fixed Width in Python
December 5, 2024 - Another method to format floating numbers is to utilize the old-style % formatting, which still works perfectly in Python 3: v = 10.4 print('% 6.2f' % v) # 10.40 print('% 12.1f' % v) # 10.4 print('2.1f' % v) # 0000000010.4 · You can assign variables for width and decimal places to make your formatting dynamic:
🌐
AskPython
askpython.com › python › string › python-floating-point-formatting
Python Floating Point Formatting: 2 Simple Methods - AskPython
April 10, 2025 - In this example, the :.2f inside the curly braces states that the floating-point number should be formatted with two decimal places. Running this code would output 123.46. ... Here, :10.2f states that the total width of the formatted string should be 10 characters, including two decimal places. The output, in this case, would be 123.46 · Python’s format method offers a versatile approach to string formatting.
🌐
Raspberry Pi Forums
forums.raspberrypi.com › board index › hardware and peripherals › raspberry pi pico › micropython
f string for fixed width output - Raspberry Pi Forums
June 10, 2023 - numbers = [ 1.234567, 12.34567, 123.4567, ] for n in numbers: print( f"9.5f: '{n:9.5f}'") 9 is total length, including the dot. 5 is the decimal places length. If number is too large and exceeds the total length, then python extends the length.