Open In App

Format a Number Width in Python

Last Updated : 15 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

Formatting numbers to a fixed width is a common requirement in various programming tasks, especially when dealing with data presentation or storage. By understanding these techniques, developers can ensure consistent and visually appealing formatting of numerical data in their Python.

Format a Number to a fixed Width in Python

In this article, we’ll explore various methods and techniques in Python to format numbers to a fixed width.

Format an Integer to a fixed Width in Python

This code demonstrates how to use f-strings in Python to format integers to fixed widths, with options to pad them with leading zeros or spaces, depending on the desired output format.

Python3




my_num = 12
 
# formatting integer to a fixed width of 3
print(f"{my_num:03d}")
   
# formatting integer to a fixed width of 4
print(f"{my_num:04d}")
   
# formatting integer to a fixed width of 6 (with leading spaces)
print(f"{my_num:6d}")


Output

012
0012
    12

Format a Floating point Number to Fixed Width

Example 1 : Using Python f-string

Format a floating point number to fixed width, in the final print statement, float_num is the name of the variable that stores our floating point number, 7.4f means we want our output number to be of width=7 , with 4 digits after the decimal point.

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.

Python3




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}")


Output

4.163476
 4.1635

Example 2: Using Python Round Function

We can use the round operator to fix the number of digits we need after the decimal point. It takes the floating point number and the number of digits as parameters.

Python3




float_num = 123.26549
 
# formatting float_num to have 4 digits after the decimal
print(round(float_num,4))


Output

123.2655

Format a Number to a Fixed Width using leading zeros

In order to use the str.zfill() function, we need to first convert the number to string. The str.zfill() function fills ‘0’s to the left of the string to make it of the required length.

Python3




my_num = 9
 
# converting number to string and then applying zfill function 
num_to_str= str(my_num)
# format my_num to fixed width of 3
result=num_to_str.zfill(3)
print(result)
 
# format my_num to fixed width of 5
result = num_to_str.zfill(5)
print(result)


Output

009
00009



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads