×

How to convert Float to Int in Python?

A float value can be converted to an int via type conversion, an explicit method of transforming an operand to a certain type. But it must be noted that such a conversion may tend to suffer from loss (loss of data). When converting an integer value, like 2, to a floating-point value, the outcome is 2.0. This conversion method is secure since no data is lost, but when converting 3.4 to an integer, the outcome is 3, which leads to a lossy conversion.

Examples:

Input:  6.77
Output: 6
Input:  4.3
Output: 4

Method 1: Using int() to convert

We can change a float value to an int using the built-in int() method, which eliminates any values past the decimal point and returns the integer/whole number component.

Syntax: int(x)
Return:  numerical value

Example 1: A float number is converted to an outcome of type int

# switching from a float to an int
number=8.6
# printing the data type as "number"
print('type:',
      type(number).__name__) 
# conversion to int
number = int(number)  
# printing the data type as "number"
print('converted value:', number,
      ', type:', type(number).__name__)

Output:

type: float
converted value: 8, type: int

Example 2:

The int() function often rounds off the result to an integer that is less than or equal to the input, even though its behaviour is neither consistent nor predictable.

number1 = 4.9
number2 = 6.99999999999999999999
number1 = int(number1)
number2 = int(number2)
print(number1, number2, sep = '\n')

Output:

4
7

Method 2: Using math.floor() and math.ceil() to convert

Using math, a float value can be transformed into the smallest integer smaller than the input.floor() function and into the largest integer bigger than the input using math.ceil() function. The math module needs to be imported to use these techniques.

Syntax: math.floor(x)
Parameter:
x: This expression uses numbers.
Returns: greatest number not exceeding x
Syntax: math.ceil(x)
Parameter:
x: It's a mathematical expression.
Returns: the smallest integer that is not zero.

Example:

In the example below, the floor() and ceil() methods were used to convert a float to an integer. While the latter provides the lowest integer larger than the input, the former returns an integer no larger than the input.

import math       
number = 6.5
floor value = math.floor(number) 
ceil_value  = math.ceil(number) 
print("the result using floor() : ",
      floor_value ,
      ', type : ',type(floor_value).__name__) 
print("the result using ceil()  : ",
      ceil_value,
      ', type: ', type(ceil_value).__name__)

Output:

the result using floor():  6, type:  int
the result using ceil():  5, type:  int

Method 3: Round conversion

A float value can be converted to an int value, the closest integer value if the second parameter is omitted. The greater integer is used when the difference is equal.

Syntax: round(x)
Parameter:
x: This expression uses numbers.
Returns: nearest integer multiple.

Example:

The round() function was used in the example below to convert from float to int; the latter produces an int number that is most like.

number =7.5
 # Ahead of time value and type
print( 'Type : ', type(number).__name__)
print( "Original number is : ", number) 
# conversion to int
value = round(num) 
print( 'Type : ',type(value).__name__)
print("the result using round  : ",value)

Output:

Type:  float
Original number is:  7.5
Type:  int
the result using round:  5

Method 4: Math.trunc() conversion

A float value can be converted into an int value. Negative integers behave like the ceiling function in the math library, and positive numbers are like the floor function.

Syntax: math.trunc(x)
Parameter:
x: This expression uses numbers.
Returns: If the number is negative, the integer should be larger; if it is positive, the integer should be smaller.

Example:

In the example below, the math.trunc() function has been used to convert from float to int. When a positive number is given, the latter produces a smaller integer number, while the former returns a larger integer number when a negative number is given.

import math
number = 6.4
number2 = -1.4
# negative numbers converted to integers
value = math.trunc(number2) 
print( 'Type of value : ',type(value).__name__)
print("the result using round  : ",value)
# positive number converted to integers
data = math.trunc(number)
print( 'Type of data: ',type(data).__name__)
print("the result using round  : ",data)

Output:

Type of value:  int
the result using round:  -1
Type of data:  int
the result using round:  6

Related Topics

Python Set intersection() method

Python Set intersection() method The set.intersection() method in Python returns a new set with elements that are similar between two or more sets. Syntax set.intersection(set1, set2 ... etc) Parameter set1- This parameter represents the set to search for...

2 minutes read.

Python Set clear() Method

Python Set clear() Method The set.clear() method removes all the elements from the set. Syntax set.clear() Parameter NA Return None Example 1 # Python program explaining # the set.clear() method # initializing the set fruits = {"watermelon", "banana", "apple"} # printing the set...

2 minutes read.

Nested Tuple in Python

If you are a Python learner, this page contains all the information that helps you know about nested tuple and how to access it in python. What is a Tuple? Multiple items...

4 minutes read.

How to Install Tweepy in Python

In this article, we will learn or understand how to install Tweepy in Python and what Tweepy is. Firstly, let’s understand What Tweepy is. As we all know, one of the...

3 minutes read.

How to Fix an EOF Error in Python?

Introduction An EOF (End-of-File) error occurs when a program tries to read beyond the end of a file or a stream, causing it to return an error message. It can happen...

8 minutes read.

Reverse a Number in Python

Python is an Object-Oriented high-level language. Python has an English-like syntax, which is very easy to read and write codes. Python is an interpreted language which means that it uses...

4 minutes read.

Python String Methods

Python String Methods Python has a set of built-in string methods. The Python string methods are as follows: capitalize() The string.capitalize() method returns a copy of the string by converting the...

5 minutes read.

Convert Float to Int in Python using Pandas

Introduction To play with huge amounts of data, in python we require a tool. The tool which is available in Python is pandas. A panda is an open-source library. It is...

4 minutes read.

Python List

The list is one of the most versatile, mutable data-structures in Python. It can store heterogeneous data or different types of data. The list contains comma-separated values (item) within the square brackets. Creating...

4 minutes read.

API Requests using Python

What is an API? API stands for Application Programming Interface. It is commonly known as API. It provides an environment that helps two or more computer programs to contact each other....

5 minutes read.

Difference between Sort and Sorted in Python

If you new to Python, it must be confusing the distinction between the Sort and Sorted functions. However, it is important to understand the differences in order to use them...

5 minutes read.

Python Tutorial

Python tutorial is a widely used programming language which helps beginners and professionals to understand the basics of Python programming easily. Python is a high-level, easy, interpreted, general-purpose, and dynamic programming...

19 minutes read.

Face Recognition in Python

In this tutorial, we will understand what is face recognition and how it is achieved in python. Face recognition is of great utility in real-world scenarios. It is an extended step...

3 minutes read.

How to Iterate through a Dictionary in Python

In this tutorial, we will learn how to interate throught the dictionary in the Python programming, using different approaches with example. Introduction to Dictionary in Python Dictionary is a special type of...

4 minutes read.

How to comment out a block of code in Python

When you are writing code in Python, you may want to document it. You need to mention why a piece of code functions, for instance. Mathematics, algorithms, and intricate business...

4 minutes read.

Python Logistic Regression with Sklearn & Scikit

In this article, we'll walk through a tutorial for utilising the Python Sklearn (formerly known as Scikit Learn) package to implement logistic regression. To assist you in remembering the concept,...

18 minutes read.

Python program to perform the arithmetic operation

Python program to perform the arithmetic operation This program will write a code to perform some basic arithmetic operations like addition, subtraction, multiplication, exponent, modulus, and division. Here we first need...

2 minutes read.

Python Line Break

Introduction In this tutorial, you will learn line breaks in python.In Python, the new line character is used to indicate the start of a new line and the end of an...

5 minutes read.

Python Basics

In this tutorial, we will learn about the basics of Python, a very famous programming language. This tutorial will help you understand the language better if you start with python....

8 minutes read.

Count Number of Keys in Dictionary Python

Dictionary is a particular data type in python. Dictionary stores unique values by taking different keys and their assigned values. Through this article, we will learn about python dictionary count,...

3 minutes read.