How to convert float to int in Python?

A floating-point value in python is a real number with a fractional component. For eg. 7.6, 5.987, 3.0 are all floating-point values. A floating-point value represents a number with more precision.

An integer is a number with no fractional part. For eg. 8, 6789, -7654 are all integer values. A floating-point value when converted to integer value results in loss of data. For example, 3.234 when converted to integer value 3 leads to lossy conversion.

This article discusses several approaches to convert a floating-point value to an integer data type in python.

Convert a float to int using the int() function

The int() function can convert a floating-point number to an integer value. This method is also known as typecasting. The int() function trims the decimal part and returns a number without any fractional component.

Consider a floating-point value 3.456 when converted to integer value results in 3. The below example illustrates the use of the int() function.

num = 3.456
print("num : ", num)
print("Type of num : ", type(num))
int_val = int(num)
print("Conversion to int_val: ", int_val)
print("Type of int_val: ", type(int_val) )

Output

num :  3.456
Type of num :  <class 'float'>
Conversion to int_val:  3
Type of int_val:  <class 'int'>

The output of the int() function is not definite. In some cases, the int() function rounds off the floating-point value to the smallest number greater than the input value.

Example,

num = 3.9999999999999999
print("Type of num : ", type(num))
int_val = int(num)
print("Conversion to int_val: ", int_val)
print("Type of int_val: ", type(int_val) )

Output

Type of num :  <class 'float'>
Conversion to int_val:  4
Type of int_val:  <class 'int'>

Convert a float to int using the math.floor() function

The floor() function can be imported from the math module. The floor() method returns the largest number not greater than the input. The syntax for the floor() method is as follows.

import math
math.floor(number)

For example,

import math
print(math.floor(3.675))
print(math.floor(-23.876))
print(math.floor(4.9999999999999))

Output

3
-24
4

Convert a float to int using the math.ceil() function

The ceil() function can be imported from the math module. The ceil() method returns the smallest number greater than the input. The syntax for the ceil() method is as follows.

import math
math.ceil(number)​

For example,

import math
print(math.ceil(3.675))
print(math.ceil(-23.876))
print(math.ceil(4.9999999999999))

Output

4
-23
5
0 results
Comment / Suggestion Section
Point our Mistakes and Post Your Suggestions