Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
int, floats, eval
#1
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 welcome all feedback.
The only dumb question, is one that doesn't get asked.
My Github
How to post code using bbtags


Reply
#2
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'
Reply
#3
The decimal is giving me what I needed. Thanks. :)
I welcome all feedback.
The only dumb question, is one that doesn't get asked.
My Github
How to post code using bbtags


Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  When is it safe to compare (==) two floats? Radical 4 650 Nov-12-2023, 11:53 AM
Last Post: PyDan
  floats 2 decimals rwahdan 3 1,588 Dec-19-2021, 10:30 PM
Last Post: snippsat
  How to avoid exec(), globals(), locals(), eval() paul18fr 10 4,905 Apr-21-2021, 05:53 PM
Last Post: snippsat
  rounding and floats Than999 2 3,046 Oct-26-2020, 09:36 PM
Last Post: deanhystad
  Stuck comparing two floats Tizzle 7 2,956 Jun-26-2020, 08:23 AM
Last Post: Tizzle
  rounding floats to a number of bits Skaperen 2 2,272 Sep-13-2019, 04:37 AM
Last Post: Skaperen
  comparing fractional parts of floats Skaperen 4 3,267 Mar-19-2019, 03:19 AM
Last Post: casevh
  eval lambda function with restricted context Olivier 7 5,071 Mar-04-2019, 10:45 PM
Last Post: Olivier
  Integer vs Floats Tazbo 2 2,843 Jan-09-2019, 12:06 PM
Last Post: Gribouillis
  eval not working in code jamminjamie 0 2,169 Dec-27-2018, 05:24 PM
Last Post: jamminjamie

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020