Format a Number Width in Python
Last Updated :
15 Feb, 2024
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
print (f "{my_num:03d}" )
print (f "{my_num:04d}" )
print (f "{my_num:6d}" )
|
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)
print (f "{my_float:7.4f}" )
|
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
print ( round (float_num, 4 ))
|
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
num_to_str = str (my_num)
result = num_to_str.zfill( 3 )
print (result)
result = num_to_str.zfill( 5 )
print (result)
|
Share your thoughts in the comments
Please Login to comment...