Python Forum
int, floats, eval - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: int, floats, eval (/thread-27911.html)



int, floats, eval - menator01 - Jun-26-2020

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.


RE: int, floats, eval - bowlofred - Jun-26-2020

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'



RE: int, floats, eval - menator01 - Jun-26-2020

The decimal is giving me what I needed. Thanks. :)