Categories
Python Answers

How to format floats without trailing zeros with Python?

Spread the love

Sometimes, we want to format floats without trailing zeros with Python.

In this article, we’ll look at how to format floats without trailing zeros with Python.

How to format floats without trailing zeros with Python?

To format floats without trailing zeros with Python, we can use the rstrip method.

For instance, we write:

x = 3.14000
n = ('%f' % x).rstrip('0').rstrip('.')
print(n)

We interpolate x into a string and then call rstrip with 0 and '.' to remove trailing zeroes from the number strings.

Therefore, n is 3.14.

Conclusion

To format floats without trailing zeros with Python, we can use the rstrip method.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

2 replies on “How to format floats without trailing zeros with Python?”

seems a little dangerous in case the number is passed as integer string (no decimal point). Signficant trailing zero would be removed.

another case to ponder
.0 or .00 are legal decimal zeros
you don’t want to strip those to empty string.
Would want to result in “0”

Leave a Reply

Your email address will not be published. Required fields are marked *