Python Forum

Full Version: int, floats, eval
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Given the scenario eval(10/2) would return 5.0 and eval(7/3) would return 2.33.
My question is how can I remove everything from the right of the decimal if it's a 0.
In the first example of eval I want the return to be 5 instead of 5.0 and if it's greater than 0 go ahead and return it like in the 2nd example.
Any help much appreciated.
I don't know a way to do this directly with format specifiers. They provide max length, not min. So if the '5.0' is printing out already, I don't think it can be trimmed without trimming all.

If you don't want to deal with special cases, you could pass the string into Decimal and then normalize it.

>>> import decimal
>>> print(decimal.Decimal('3.24').normalize())
3.24
>>> print(decimal.Decimal('5.00').normalize())
5
A cheesier way is just to remove any zeros on the right, then remove any decimals on the right.

>>> '3.24'.rstrip('0').rstrip('.')
'3.24'
>>> '5.00'.rstrip('0').rstrip('.')
'5'
But if you do it that way, you can't pass it strings without the decimal or you'll have problems.

>>> '500'.rstrip('0').rstrip('.')
'5'
The decimal is giving me what I needed. Thanks. :)