How to Convert float to int in PythonWe have used different numeric data types in Python, in this tutorial we will learn how we can convert a float value to an integer value. Let's have a look at the approaches to implement the same-
So, let's get started with the first one- Using trunc()The following program shows how we can use trunc() to convert a float value to an integer in Python. Output: The result of a + b + c is 42.33 The converted value of a is: 20 The converted value of b is: 12 The converted value of c is: 9 The converted value of sum is: 42 Explanation- It's time to understand what happened in the above program-
In the next program, we will make use of floor(). Using floor()First, let's understand what happens when we pass a float value in floor()? When a float number is passed in floor(), it rounds off the number down to the nearest integer. Consider the program given below, Output: The result of a + b + c is 42.33 The converted value of a is: 20 The converted value of b is: 12 The converted value of c is: 9 The converted value of sum is: 42 Explanation- Let's have a glance at the explanation of this program.
Now, we shall see how ceil() can be used to do the same. Using ceil()First, let's understand what happens when we pass a float value in ceil()? When a float number is passed in ceil(), it rounds off the number up to the nearest integer. Output: The result of a + b + c is 42.33 The converted value of a is: 21 The converted value of b is: 13 The converted value of c is: 10 The converted value of sum is: 43 Explanation- Let's understand what we have done in this program.
Finally, in the last program, we will use the most basic approach of converting a float value to an integer which is using int(). Using int()The program given below illustrates how it can be used in a program. Output: The result of a + b + c is 42.33 The converted value of a is: 20 The converted value of b is: 12 The converted value of c is: 9 The converted value of sum is: 42 Explanation-
ConclusionIn this tutorial, we learned the interesting methods of converting a float to an integer in Python. Next TopicMultiply All Elements in list of Python |
We provides tutorials and interview questions of all technology like java tutorial, android, java frameworks
G-13, 2nd Floor, Sec-3, Noida, UP, 201301, India