1

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.

mskfisher
  • 3,291
  • 4
  • 35
  • 48
user973057
  • 23
  • 3

2 Answers2

4

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'>
Cameron
  • 96,106
  • 25
  • 196
  • 225
2

Probably you're looking for both round and int:

>>> foo = 1.9
>>> int(foo)
1
>>> int(round(foo))
2
agf
  • 171,228
  • 44
  • 289
  • 238