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.
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”