Question

If I want to convert a float to an integer in Python, what function do I use?

The problem is that I have to use a variable passed through the function math.fabs (Absolute Value) as an index for a list, so it has to be an int, while the function math.fabs returns a float.

Was it helpful?

Solution

Use the int() constructor:

>>> foo = 7.6
>>> int(foo)
7

Note that if you use the built-in abs() function with an integer argument, you'll get an integer result in the first place:

>>> type(abs(-7))
<type 'int'>

OTHER TIPS

Probably you're looking for both round and int:

>>> foo = 1.9
>>> int(foo)
1
>>> int(round(foo))
2
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top