Python Forum

Full Version: Converting float (2.0) to integer(2)
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
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
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.
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))