Skip to content
Tactiverge

Python reference

int and float

Also called: integer · floating point · type conversion · int() · float()

Definition

Python's int holds whole numbers of any size exactly; float holds real numbers approximately, in 64-bit binary floating point with about 15 to 16 significant digits.

Picture it

Counting things (pixels, steps, loop passes) wants ints; measuring things (volts, metres) wants floats. Dividing with / always gives a float, even 6 / 3. int() truncates towards zero rather than rounding.

Worked example

What do int(7.9), int(-7.9), round(2.5) and 6 / 3 give?

  1. int truncates towards zero: 7 and -7
  2. round uses banker's rounding: round(2.5) = 2
  3. / always returns a float: 2.0

Answer7, -7, 2 and 2.0.

✓ The 3 numbers in this answer are recomputed from scratch by an automated test.

In Python

print(int(7.9), int(-7.9))  # 7 -7
print(round(2.5), round(3.5))  # 2 4  (round half to even)
print(type(6 / 3))  # <class 'float'>

Common misconceptions

  • Misconception: int() does not round; it chops off the fractional part.
  • Misconception: round(2.5) is 2 in Python 3, because ties round to the even neighbour.