TarGz TarGz - 1 year ago 89
Python Question

Formatting floats in Python without superfluous zeros

How to format a float so it does not containt the remaing zeros? In other words, I want the resulting string to be as short as possible..?


3 -> "3"
3. -> "3"
3.0 -> "3"
3.1 -> "3.1"
3.14 -> "3.14"
3.140 -> "3.14"

Answer Source

Me, I'd do ('%f' % x).rstrip('0').rstrip('.') -- guarantees fixed-point formatting rather than scientific notation, etc etc. Yeah, not as slick and elegant as %g, but, it works (and I don't know how to force %g to never use scientific notation;-).

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download