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.