Safest way to convert float to integer in python?

后端 未结 10 2524
不思量自难忘°
不思量自难忘° 2020-11-27 13:44

Python\'s math module contain handy functions like floor & ceil. These functions take a floating point number and return the nearest integer be

相关标签:
10条回答
  • 2020-11-27 14:07

    Since you're asking for the 'safest' way, I'll provide another answer other than the top answer.

    An easy way to make sure you don't lose any precision is to check if the values would be equal after you convert them.

    if int(some_value) == some_value:
         some_value = int(some_value)
    

    If the float is 1.0 for example, 1.0 is equal to 1. So the conversion to int will execute. And if the float is 1.1, int(1.1) equates to 1, and 1.1 != 1. So the value will remain a float and you won't lose any precision.

    0 讨论(0)
  • 2020-11-27 14:09

    Use int(your non integer number) will nail it.

    print int(2.3) # "2"
    print int(math.sqrt(5)) # "2"
    
    0 讨论(0)
  • 2020-11-27 14:14

    You could use the round function. If you use no second parameter (# of significant digits) then I think you will get the behavior you want.

    IDLE output.

    >>> round(2.99999999999)
    3
    >>> round(2.6)
    3
    >>> round(2.5)
    3
    >>> round(2.4)
    2
    
    0 讨论(0)
  • 2020-11-27 14:14

    df['Column_Name']=df['Column_Name'].astype(int)

    0 讨论(0)
提交回复
热议问题