Python Forum
Converting float (2.0) to integer(2)
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Converting float (2.0) to integer(2)
#1
HI,

Iam python beginner. Kindly help me. My query is, i want to round off float value to 2 decimals. if the number is 2 or 2.0 then the number to be converted into integer.

Question: lst = [2,3.96343,5.635,2.32463255,7.0,12,1.0]
Output: lst = [2,3.96,5.64,2.32,7,12,1]

lst=[2,3.96343,5.635,2.32463255,7.0,12,1.0]
k=[]
for i in lst:
    if len(str(i))==1:
        k.append(i)
    elif len(str(i))==3 and str(i)[-1]==0:
        k.append(int(i))

    else:
        k.append(round(i,2))
    
print(k)
the above code returning the output is : [2, 3.96, 5.63, 2.32, 7.0, 12, 1.0]. But it is wrong output.

Regards
Raj Kumar
Reply
#2
If you encounter things like this, the best way is to break the lines in smaller steps to see what goes wrong.
>>> str(1.0)[-1] == 0
False
>>> str(1.0)[-1] == '0'
True
Then you can see you are comparing a string with an integer. The result is False because a string is not an integer. But you should compare a string with a string. Then you get what you want.
Reply
#3
The float has the method is_integer().
You can use it.

By the way, if you expect different results with rounding, it's
scientific rounding: Half to even.

lst = [2, 3.96343, 5.635, 2.32463255, 7.0, 12, 1.0]
k=[]
for i in lst:
    if isinstance(i, int):
        k.append(i)
    elif isinstance(i, float):
        if i.is_integer():
            k.append(int(i))
        else:
            k.append(round(i,2))
Almost dead, but too lazy to die: https://sourceserver.info
All humans together. We don't need politicians!
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  python calculate float plus float is incorrect? sirocawa 6 253 Apr-16-2024, 01:45 PM
Last Post: DeaD_EyE
  converting user input to float troubles RecklessTechGuy 3 2,447 Aug-17-2020, 12:41 PM
Last Post: deanhystad
  How to check if user entered string or integer or float?? prateek3 5 11,328 Dec-21-2019, 06:24 PM
Last Post: DreamingInsanity
  Comaparing Float Values of Dictionary Against A Float Value & Pick Matching Key firebird 2 3,382 Jul-25-2019, 11:32 PM
Last Post: scidam
  cannot convert float infinity to integer error despite rounding off floats Afterdarkreader 3 15,198 Dec-15-2017, 02:01 AM
Last Post: micseydel
  Storing float as integer in a database Ageir 6 5,238 Aug-17-2017, 08:03 PM
Last Post: Ageir

Forum Jump:

User Panel Messages

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