How to Convert Float to Int in Python
Kay Jan Wong 21 Apr 2023 3 min read
Python is the programming language of choice for many data scientists because of its rich expanse of libraries and easy-to-understand syntax. Regardless, it still requires time and investment to learn. Everyone who has taken a language course knows that becoming fluent requires a solid foundation. And just like you can’t form English sentences without knowing individual words, learning data types is crucial to chaining codes together. That’s why, without a doubt, if you are new to Python programming, it’s important to understand the different types, such as number (int and float), string, and boolean.
This tutorial will help you get started by introducing you to the int and a float in Python and demonstrating how to perform data type conversion using NumPy.
Table of Contents
What Are Float and Int in Python?
Data can be represented by numeric values such as:
- Monetary value
- Age
- Counts
In Python, int and float are two widely used data types for numeric values. Int represents integers – either a positive or negative whole number like 3 or 5. Meanwhile, floats (or floating points) are real numbers, such as 4.37 or 55.87. The difference between the 2 is simply the presence of a decimal point.
You can find out what your variable is by applying type()in Python:
How to Convert Float to Int in Python
In some cases, we do not need the results of mathematical calculations with a decimal place precision. That means we do not need our variable to be a float. So, what do we do?
We can perform something called “casting a floating-point number to an integer” to convert our data types. Essentially, it’s transforming a float to an int in Python.
To carry out this operation, you need to apply int() around a value or variable:
However, you should use this technique with caution, as all floating-point numbers are rounded down to the nearest integer by default:
Rounding Up and Down using NumPy
Instead of using casting to convert float to int, we can apply round() to a value or variable and it automatically rounds up or down the number:
This is useful for mathematical operations as you would not want to obtain the incorrect answer just because of rounding errors.
How to Convert Float to Int in Python Using NumPy
You can control which way Python rounds your floating points. Strictly speaking, this method is for mathematical equations that take the floor (rounded down) or ceiling (rounded up) version of numbers. For example, if a problem asks for the maximum number of items you can buy with a given amount of money, the answer must be rounded down to the nearest integer. Why? Because you cannot purchase a fraction of an item, nor can you round up and buy more than you can afford.
To apply a default command, you need the NumPy library. First, you need to import the package to Python, then set your desired outcome:
Important note: NumPy does not perform casting automatically, so you still have to apply int() to the result.
Type conversions are a useful skill in Python when you want to control the representation of numerical data. It is easy to perform type conversion, but tricky as it can lead to rounding errors if used incorrectly.
Float to Int in Python: Next Steps
Fluency in a programming language like Python is essential for anyone looking to land a job as a data scientist in the field. Often, employers will set you tasks during the interview, so make sure you know your way around the different data types. It’s generally good practice to brush up on your coding and data skills now to ensure a successful data science career tomorrow. Thankfully, you’ve come to the right place
The 365 Data Science Program offers self-paced courses led by renowned industry experts. Starting from the very basics all the way to advanced specialization, you will learn by doing with a myriad of practical exercises and real-world business cases. If you want to see how the training works, start with a selection of free lessons by signing up below.
Learn data science with industry experts
Kay Jan is a Data Scientist and writer with a Bachelor’s degree in Engineering and Master’s in Computing. Her experience includes working for some of the world’s leading financial service and business advisory providers. In 2018, she started her e-learning journey to continue improving her professional skills and knowledge. Kay finds fulfilment in giving back to the data science community through teaching and writing.
Convert Floating-Point Number to an Integer in Python
Converting a floating number to an integer in Python is relatively easy thanks to the in-built functions and libraries. When converting a floating number to an integer, we have two possibilities. Though it is easy to write a function ourselves to do this task, we will only talk about how to use the in-built functions and libraries in this article.
Suppose we have a number, say 1.52 . If we wish to convert this number to an integer, we can either go with 2 or 1 . The former is the ceiling value, and the latter is the floor value. Since there are several functions to do this task, they all carry out the above task differently and return different values. So choose the function accordingly based on your use case.
Convert Floating-Point Number to Integer Using int() Function in Python
The int() function accepts an argument representing a number and converts it to an integer. This argument can be a string, a float value, or an integer itself. The function considers the integer value or part before the decimal in the number and returns it.
But int() acts a bit differently when a number of the form integer.9999999999999999 is passed as an argument. When there are more than or equal to sixteen 9 digits after the decimal, the function returns integer + 1 in case of a positive value and integer — 1 in case of a negative value as an answer.
Refer to the following code snippet for a better understanding of the concept.
Convert Floating-Point Number to Integer Using math Module in Python
We can achieve the same task by using an in-built Python library, math . This library has all sorts of mathematical functions required for mathematical calculations.
We’ll talk about only three mathematical functions from the math library.
As the name suggests, the trunc() function truncates or cuts or removes the decimal part of the number passed as an argument and only considers the integer part. It behaves exactly the same as the in-built int() function and behaves differently for the exception we talked about above.
Refer to the official documents to learn more about the function, here
Next, we have the ceil() function. This function returns the ceiling value of the number or the smallest integer greater than or equal to the number passed as an argument.
Refer to the official documents to learn more about the function, here
Lastly, we have the floor() function. This function returns the floor value of the number or the largest integer that is less than or equal to the number passed as an argument.
Refer to the official documents to learn more about the function, here
Vaibhav is an artificial intelligence and cloud computing stan. He likes to build end-to-end full-stack web and mobile applications. Besides computer science and technology, he loves playing cricket and badminton, going on bike rides, and doodling.
Python Float to Int
Summary: in this tutorial, you’ll learn how to convert a float to an integer.
Suppose that you have a float such as 20.3, and you want to convert it to an integer.
When you convert a float to an integer, you’ll have a data loss. For example, 20.3 may become 20 or 21 .
Python provides you with some functions in the math module for converting from a float to an int , including:
- Truncation
- Floor
- ceiling
Truncation
The trunc(x) function returns the integer part of the number x . It ignores everything after the decimal point. For example:
Similarly, the int() constructor accepts a float and uses truncation to cast a float to an int :
Floor
The floor(x) function returns the largest integer less than or equal to x . For example:
The following shows how floor() function is applied to a positive number:
For positive numbers, floor(x) and trunc(x) return the same result. However, it’s not the case for negative numbers. For example:
The following picture shows how the floor() function is applied to a negative number:
The following picture illustrates the difference between the floor() and trunc() function when you apply them to a negative number:
Ceiling
The ceil(x) function returns the smallest integer greater than or equal to x . For example:
The following illustrates how the ceil() function is applied to a positive number:
This example uses the ceil() function for negative numbers:
The following illustrates how the ceil() function is applied to a negative number:
Python Program to Convert Float to Int
Irrespective of what language you are programming in, data types play a major part in your program. There are various types of programming language to deal with and hence, there are times when you get stuck to converting them into one form to another. In this article, let us study how you can convert float data type to int data type in python using various external methods and their respective outputs. But before jumping to type conversions, let us have a flashback to the introduction of float and integer data types.
What is Integer in Python?
Integer in python can be treated as the whole number which can be either positive or negative. As an integer is considered to be the whole number, it does not consist of any decimal points and hence can extend up to the computer’s limit. Int is by default decimal, i.e., base 10 although you can later convert it from one form to another. Let us understand int data type better with the example below:
For example:
Output:
What is Float in Python?
Well, the float-point data type is no more different than an integer in python. Unlike integer data types, float-point consist of any number with a decimal point. According to IEEE 754 standards, the float-point data type is a 64-bit double-precision number. You can generally define them with the binary fractions(base-2) and later convert them to any other form using type conversion.
For example:
Output:
How to Convert Float to Int in Python?
Below are some of the methods by which you can convert float to int in python.
1) Using int() method
Python provides multiple in-built methods which help you to ease your programming. Int() is one such method used to convert any data type into an integer with minimal steps. The function takes the float-point variable as the argument and trims the values after the decimal points. As the result, the final output will be the integer or whole number. Let’s understand the working of the int() method with the example below:
For example:
Output:
Remember that in most cases, the int() function rounds off the results to the integer lesser than the decimal point. However, sometimes there’s an exception hence we cannot predict or define the behavior for the same.
For example:
Output:
2) Using math.floor() and math.ceil()
If you have already decided to convert float value to an int value no larger than the input, make use of the floor() method and pass the value as the parameter to the method. Whereas, if you wish to convert it to a value greater than the original, make use of the ceil() method as shown in the example below:
For example:
Output:
Note that floor() and ceil() methods are the part of math() library and therefore, you need to import the math library before using it.
3) Using trunc() method
Python provides the in-built function i.e., trunc() method which helps to provide the integer value. Here, the method takes the float-point value as the parameter and ignores everything after the decimal point. Let us understand the use of trunc() method in the example below:
For example:
Output:
4) Using numpy library
Till now, you studied how to convert a single floating-point to an integer value. But what if you are provided with the collection of multiple float values and need to get the corresponding integer values from it. In this case, you have to import the NumPy library and make use of the astype() method. Doing this will provide you with the integer value as shown in the below example:
For example:
Output:
Limitations for Converting Float to Int in Python
- Although you use the int() method for type conversions it is not recommended to use as there could be the chances of data loss.
- You can make use of the math module to avoid the loss of data. However, the situation of data loss does not change if the function is not used wisely.
Conclusion
Type conversion plays an important role while programming your code irrespective of the language you use. In this article, we studied how you can convert float to int in python using various explicit methods and their corresponding example. It is recommended to get good command on these conversions for better and more efficient programming practice. To learn more about such type conversions in python, visit our blogs at favtutor.