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
Linda HamiltonOriginal
2024-11-30 07:06:18263browse

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:

  • 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))

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!

Statement:
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