Python Forum
Converting float (2.0) to integer(2) - 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: Converting float (2.0) to integer(2) (/thread-23013.html)



Converting float (2.0) to integer(2) - Raj_Kumar - Dec-07-2019

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


RE: Converting float (2.0) to integer(2) - ibreeden - Dec-07-2019

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.


RE: Converting float (2.0) to integer(2) - DeaD_EyE - Dec-07-2019

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))