Home >Backend Development >Python Tutorial >How to Format Floating-Point Numbers to a Fixed Width in Python?
Formatting Floating Numbers to Fixed Width in Python
When displaying floating-point numbers, it's often necessary to format them to a specific width while fulfilling certain requirements. These requirements may include leading zeros, trailing decimal zeros, truncation of excessive decimal digits, and alignment of decimal points.
To achieve this in Python, we can utilize the format string syntax as follows:
number = 23.234567 # Format to fixed width with 6 digits, including decimal points print("{:10.4f}".format(number))
The output will be like this:
23.2346
In this case, the format specifier consists of:
10.4f after the colon:
Using this technique, you can customize the formatting of floating-point numbers based on your requirements. For example, the following code prints a list of floating-point numbers to a fixed width of 10 characters, including trailing decimal zeros:
numbers = [23.23, 0.123334987, 1, 4.223, 9887.2] for number in numbers: print("{:10.4f}".format(number))
Output:
23.2300 0.1233 1.0000 4.2230 9887.2000
The above is the detailed content of How to Format Floating-Point Numbers to a Fixed Width in Python?. For more information, please follow other related articles on the PHP Chinese website!