- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to format a floating number to fixed width in Python?
Floating numbers are the numbers which include a decimal point and in other words are also called as real numbers. By default, the number of decimal points in floating number is 6 but we can modify that using the methods given below.
In this article, we are going to find out how to format a floating number to given width in Python.
The first approach is by using the format method. We will include the format in a print statement and we will reference using the curly braces and we should mention the number of decimal points inside the curly braces.
Example
In the program given below, we are taking a floating number as input and we are rounding it off to 4 decimal points using the format() method −
num = 123.26549 print("Given floating number is") print(num) print("The floating number rounded up to 4 decimal points is") print("{:12.4f}".format(num))
Output
The output of the above example is given below −
Given floating number is 123.26549 The floating number rounded up to 4 decimal points is 123.2655
Using % operator
The second approach is by using the % operator. It is similar to the format method but instead of the format we will use % and we will also use % instead of the curly braces.
Example
In the example given below, we are taking a floating number as input and we are rounding it off into 4 decimals using % operator −
num = 123.26549 print("Given floating number is") print(num) print("The floating number rounded up to 4 decimal points is") print("% .4f" %num)
Output
The output of the above example is given below −
Given floating number is 123.26549 The floating number rounded up to 4 decimal points is 123.2655
Using round operator
The third approach is by using the round operator. We will mention the number and the number of decimal points in the round operator and it will return us the updated number as output.
Example
In the program given below, we are taking a floating number as input and we are rounding it off into 4 decimal points using the round method −
num = 123.26549 print("Given floating number is") print(num) print("The floating number rounded up to 4 decimal points is") print(round(num,4))
Output
The output of the above example is as shown below −
Given floating number is 123.26549 The floating number rounded up to 4 decimal points is 123.2655