Home > Backend Development > Python Tutorial > How to Format Floating-Point Numbers to a Fixed Width in Python?

How to Format Floating-Point Numbers to a Fixed Width in Python?

Linda Hamilton
Release: 2024-11-30 07:06:18
Original
274 people have browsed it

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))
Copy after login

The output will be like this:

   23.2346
Copy after login

In this case, the format specifier consists of:

  • Empty string before the colon (:): Indicates the next argument to be formatted.
  • 10.4f after the colon:

    • f: Fixed-point notation
    • 10: Total width of the field (left-padded with spaces)
    • 4: Number of digits after the decimal point

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))
Copy after login

Output:

   23.2300
   0.1233
   1.0000
   4.2230
 9887.2000
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template