Skip to content
Advertisement

Formatting a float number without trailing zeros

When I do a simple division in Python 3, such as 123000/1000, I get 123.0, or 4/2 I get 2.0. How do I get rid of the trailing zero in Python 3’s division?

EDIT: I don’t want just simple integer division. For ex, 1234/1000 should give 1.234. To be clear, this question is about formatting the output, not internal representation.

Advertisement

Answer

Thanks all for your help! The answer came from @vaultah:

>>> f'{2.1:g}'
'2.1'
>>> f'{2.0:g}'
'2'

So just use regular division such as 4/2 and then format the string. From the docs for ‘g’: https://docs.python.org/2/library/string.html#format-specification-mini-language “insignificant trailing zeros are removed from the significand, and the decimal point is also removed if there are no remaining digits following it.”

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement