Format Floating Number to Fixed Width in Python



In Python formatting a floating point number to a fixed width can be done by using methods like Python's f-strings and the flexible format() method.

Float formatting methods

The two built-in float formatting methods are as follows

  • f-strings: Convenient way to set decimal places, spacing and separators.

  • str.format(): This method allows to formatting types inside the placeholders to control how the values are displayed.

Using f-strings

We can format a floating-point number to a fixed width by using Python's f-strings, in below code '.2f' specifies that the number should formatted as a floating-point number with 2 decimal places.

Example

number = 123.4568
formatted = f"{number:10.2f}"
print(formatted)

Output

  123.46

Using str.format() method

The str.format() method is versatile in formatting strings in Python. By using this method we can also control padding and alignment.

Example

number = 123.4568
formatted = "{:10.2f}".format(number)
print(formatted)

Output

  123.46

Padding and Alignment using str.format()

We can also control padding and allignment by using this str.format() method, some examples are as follows.

  • Right Align with Padding: This will right-align the number or text by specifying the total width.

  • Left Align with Padding: This will left-align the number or text by specifying the total width.

  • Center Align: This will center-align the number or text with spaces.

  • Zero Padding: To Pad the number with zero's on the left side instead of spaces.

Example

The below example determines padding and alignment of given number using. The '10' number specifies the total width.

number = 838.65
# right align with spaces
right_align_formatted = "{:>10}".format(number)
print('Right Align with Padding :',right_align_formatted)

# left align with spaces
left_align_formatted = "{:<10}".format(number)
print('Left Align with Padding :',left_align_formatted)

# center align with spaces
formatted = "{:^10}".format(number)
print('Center Align :',formatted)

# padding with zeros
zero_padding = "{:010.2f}".format(number)
print('Zero Padding :',zero_padding) 

Output

Right Align with Padding :      838.65
Left Align with Padding : 838.65    
Center Align :   838.65  
Zero Padding : 0000838.65
Updated on: 2024-11-13T13:50:54+05:30

6K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements