"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to Remove Trailing Zeros from Floating-Point Numbers in Python?

How to Remove Trailing Zeros from Floating-Point Numbers in Python?

Posted on 2025-02-26
Browse:722

How to Remove Trailing Zeros from Floating-Point Numbers in Python?

Removing Trailing Zeros from Float Formatting

When displaying floating-point numbers, it's often desirable to remove any trailing zeros to achieve a more concise representation. This article explores how to format floats in Python without these unnecessary zeros.

The %g Format Specifier

One approach to eliminating trailing zeros is to use the %g format specifier. This specifier ensures that:

  • Trailing zeros in the significant (non-zero) portion of the number are removed.
  • The decimal point is omitted if there are no remaining digits after it.

Example:

>>> print('%g' % 3.140)
3.14

Alternative Methods with Python 2.6

In Python 2.6 and later, alternative formatting methods are available:

  • With the .format() method:
>>> '{0:g}'.format(3.140)
3.14
  • With f-strings (Python 3.6 ):
>>> f'{3.140:g}'
3.14

Explanation

According to the Python documentation for the format() specifiers, the %g format specifier is defined as follows:

"Remove insignificant trailing zeros and the decimal point if there are no remaining digits following it."

This behavior aligns with the desired outcome of removing trailing zeros for a more compact float representation.

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3