Force division to return a floating-point number in Python

Borislav Hadzhiev

Last updated: Jul 11, 2022

Photo from Unsplash

**Use the division / operator to force division to return a floating-point
number, e.g. result_1 = 25 / 5. Division / of integers always returns a
float, while floor division // of integers always returns an integer.**

main.py

`result_1 = 25 / 5 print(result_1) # 👉️ 5.0 print(type(result_1)) # 👉️ <class 'float'>`

Division `/`

of integers always returns a floating-point number in Python 3.

If you use Python 2, import `division`

from `__future__`

at the beginning of the
file.

main.py

`# 👇️ only necessary if you use Python 2 from __future__ import division result_1 = 25 / 5 print(result_1) # 👉️ 5.0 print(type(result_1)) # 👉️ <class 'float'>`

Division

`/`

of integers yields a float, while floor division `//`

of integers result in an integer.The result of using the floor division operator is that of a mathematical
division with the `floor()`

function applied to the result.

main.py

`my_num = 50 print(my_num / 5) # 👉️ 10.0 (float) print(my_num // 5) # 👉️ 10 (int)`

An alternative to importing `division`

from `__future__`

is to convert the
divisor to a float.

main.py

`result_1 = 25 / float(5) print(result_1) # 👉️ 5.0 print(type(result_1)) # 👉️ <class 'float'>`

If the divisor is a floating-point number, the result will be a float.

The best way to force division to return a floating-point number is to upgrade to Python 3 and use the division

`/`

operator.If you use Python `3`

, division of integers or floating-point numbers always
yields a floating-point number.