The Wayback Machine - https://web.archive.org/web/20240605025305/https://www.geeksforgeeks.org/format-a-number-width-in-python/
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



Similar Reads

Python program to print number of bits to store an integer and also the number in Binary format
Given an integer, the task is to write a Python program to print the number of bits to store that integer and also print the same number in Binary format. Example: Input: n = 10 Output: Number of bits to store the number: 4 Binary value: 0b1010 Input: n = 120 Output: Number of bits to store the number: 7 Binary value: 0b1111000 The Task can be done
4 min read
Converting a 10 digit phone number to US format using Regex in Python
Text preprocessing is one of the most important tasks in Natural Language Processing. You may want to extract number from a string. Writing a manual script for such processing task requires a lot of effort and at most times it is prone to errors. Keeping in view the importance of these preprocessing tasks, the concept of Regular Expression have bee
1 min read
Python Program to Convert a Number into 32-Bit Binary Format
Binary representation is a fundamental concept in computer science, and converting numbers into binary format is a common task for programmers. In this article, we will explore some simple and generally used methods to convert a number into a 32-bit binary format using Python. Each method provides a unique approach to achieve the same result. Conve
3 min read
Getting screen's height and width using Tkinter | Python
Tkinter provides some methods with the help of which we can get the current screen height and width.Following methods can be used to decide height and width : winfo_screenheight() // Returns screen height in pixels winfo_screenmmheight() // Returns screen height in mm winfo_screenwidth() // Returns screen width in pixels winfo_screenmmwidth() // Re
1 min read
Python PIL Attributes | Image.width Method
PIL is the Python Imaging Library which provides the python interpreter with image editing capabilities. The Image module provides a class with the same name which is used to represent a PIL image. The module also provides a number of factory functions, including functions to load images from files, and to create new images. The Image class have th
1 min read
turtle.width() function in Python
The turtle module provides turtle graphics primitives, in both object-oriented and procedure-oriented ways. Because it uses Tkinter for the underlying graphics, it needs a version of Python installed with Tk support. turtle.width() This method is used to set or return the line thickness. Set the line thickness to width or return it. If resizemode i
2 min read
Python VLC MediaPlayer - Getting Width of selected video
In this article we will see how we can get the width of the MediaPlayer object in the python vlc module. VLC media player is a free and open-source portable cross-platform media player software and streaming media server developed by the VideoLAN project. MediPlyer object is the basic object in vlc module for playing the video. We can create a Medi
2 min read
How to Change the Line Width of a Graph Plot in Matplotlib with Python?
Prerequisite : Matplotlib In this article we will learn how to Change the Line Width of a Graph Plot in Matplotlib with Python. For that one must be familiar with the given concepts: Matplotlib : Matplotlib is a tremendous visualization library in Python for 2D plots of arrays. Matplotlib may be a multi-platform data visualization library built on
2 min read
Change the ratio between width and height of an image using Python - Pillow
Python Imaging Library (expansion of PIL) is the de facto image processing package for the Python language. It incorporates lightweight image processing tools that aid in editing, creating, and saving images. This module is not preloaded with Python. So to install it execute the following command in the command-line: pip install pillowTo change the
2 min read
How to find width and height of an image using Python?
In this article, we are going to discuss how to get the height and width of a particular image. In order to find the height and width of an image, there are two approaches. The first approach is by using the PIL(Pillow) library and the second approach is by using the Open-CV library. Approach 1: PIL is the Python Imaging Library is an important mod
3 min read
Article Tags :
Practice Tags :