×

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

Joint Plot in Python

Introduction to Joint plots: The joint plot is the finest approach to evaluate both the specific distribution of each variable and also the connection between the two variables. Three different plots make...

4 minutes read.

How to check version of Python

How to check version of python The versions of Python come with different kinds of features and functionalities. It is not a herculean task to keep track of the updates these...

3 minutes read.

Dictionary to JSON Python

In python JSON (JavascriptObject Notation). In the programming language, the text file is made using the script file.We can use many built-in packages which arenamedJSON.Before using the packages, we have...

3 minutes read.

How to set font for Text in Python

As a tuple with the font family as the first component, a size in point as the second, and possibly a string with one or more of the style modifiers...

5 minutes read.

String indices must be integers in Python

Lists, tuples, and strings are examples of iterable objects in Python whose items or characters can be retrieved by their index numbers. For instance, you might take the following action to...

3 minutes read.

Python Dictionary values() method

Python Dictionary values() method The dictionary.values() method in Python returns a view object that displays a list of all the values in the specified dictionary. Syntax dictionary.values() Parameter NA Return This method returns a view object. The...

1 minute read.

Writing to a CSV file 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...

6 minutes read.

Python GUI Programming

GUI (Graphical User Interface) GUI is a graphics-based operating system that uses icons and menus to interact with the user. Python mostly works on CLI (Command Line Interface). Widgets Any user interface has...

4 minutes read.

List Index out of Range Python for Loop

The List is generally used in Python to store multiple items or elements inside one single variable. The List is ordered in nature, the List can contain the elements inside...

3 minutes read.

Difference between Python 2 and Python 3

In this tutorial, we will learn the differences between two versions of python, that is, python version 2 and python version 3. Some basic differences include- Python 2 is the older version...

3 minutes read.

Nested for Loop in Python

"Loop" is one of the foundation concepts to learn programming in any language. Nested loops are significant steps in solving many types of problems, ranging from basic to complex scenarios....

9 minutes read.

Python Tuple index() Method

Python Tuple index() Method The tuple.index() method of Python finds the first occurrence of the specified value and returns its index if the value is found else raises an exception if...

1 minute read.

Python Operators

Operators in Python programming An operator is a symbol that operates on one or more operands. An operand is a value or a variable on which we perform the operation....

5 minutes read.

Genetic Algorithm in python

Python : Python is an object oriented programming language which is highly interpreted and is highly interactive. Python was created by Guido van Rossum in the year 1985 – 1990 .The source...

4 minutes read.

Commands in Python

In this tutorial, we will see some of the widely used python commands along with their syntaxes and examples. To make Python more user-friendly, developers have provided these commands to...

12 minutes read.

Python Set isdisjoint() method

Python Set isdisjoint() method The set.isdisjoint() method in Python returns a boolean value True if two sets are disjoint sets ( i.e. none of the elements are present in both sets), otherwise it returns...

1 minute 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.

Salary of Python Developers in India

In this tutorial, we will understand who python developers are and what is their salary when they work in India. Python Developers Python Developers are the people who are involved in designing...

4 minutes read.

How to Parse JSON in Python

JSON The JSON, the Java Script Object Notation, is an open standard file designed for data interchange; it is light-weighted text. The JSON uses human-readable text to store and transmit the...

4 minutes read.

Python List Methods

Python List Methods Python has a set of built-in methods that you can use on lists or arrays. Following are all of the methods of list objects: Methods Explanation append The list.append() method...

3 minutes read.