How to convert floating point numbers to integers in Python

Let’s consider you want to convert a floating point number into an integer. There are two ways of doing that.

Method 1 – Truncating

You can truncate the floating point number to just the portion before the decimal point. You can do that with the int() function which truncates the number towards zero.

>>> fpn = 57.83
>>> int(fpn)
57

Alternatively, there is a function that will truncate floating point numbers to only the integer part. It is part of the math module and it is called math.trunc()

>>> import math
>>> fpn = 57.83
>>> math.trunc(fpn)
57

Both, int() and math.trunc() truncate floating point numbers to only the integer part.

Method 2 – Rounding

You can round the floating point number to the nearest integer. So, what about this one:

>>> fpn = 57.83
>>> round(fpn)
58.0
>>> int(round(fpn))
58

You can round to only one decimal place for example, using the round() method.

>>> fpn = 57.83
>>> round(fpn, 1)
57.8

You can also convert floating point numbers to integers and round them up or down using the ceil() or floor() methods.

>>> import math
>>> fpn = 57.83
>>> int(math.floor(fpn))
57
>>> int(math.ceil(fpn))
58

Leave a Reply