Table of Contents
Quick Solution
To Remove decimals in Python, useint()
function.
1234 a =3.7print(int(a))Or use
math.trunc()
12345 import matha=3.7print(math.trunc(a))Output
3Please note that when we remove decimal places, number before decimal point(
.
) will remain the same. If you want to round it up or down, then you should use round() instead.
Two of the most common types to represent numeric values are int
and float
. The int
type is used to represent a certain range of integers. The float
type represents values with fractional parts. The latter requires more memory and also represents a wider range than the int
type.
Remove Decimal Places in Python
In this article, we will discuss how to remove decimal places in Python. For this, we will convert the float
values to an integer.
Using the int()
function
The int()
function is used to typecast a value to an integer. To remove decimal places in Python we will pass a float
value with a decimal part to this function and it will remove decimal places in Python.
For example,
1 2 3 4 |
a =2.7 print(int(a)) |
Output
In the above example, we convert the float
value to an integer and the decimal places are discarded.
Using the math
library
The math
library is used in Python to provide functions and constants that can calculate complex mathematical calculations. We can remove decimal places in Python using the truncate()
function from the math
library.
This function takes a float
value and removes the decimal part from the same, returning the integer value.
See the code below.
1 2 3 4 5 |
import math a =2.7 print(math.trunc(a)) |
Output:
We can also use the floor()
and ceil()
functions from this library. The former function returns the largest integer smaller than the given number and the latter returns the smallest integer greater than the provided value.
It will round off the float
value and return the calculated integer value.
For example,
1 2 3 4 5 6 |
import math a =2.7 print(math.floor(a)) print(math.ceil(a)) |
3
Further reading:
Using string formatting
String formatting refers to the technique of getting the output string in our desired format. Using the %d
specifier we can get the output as an integer.
See the code below.
1 2 3 4 |
a =2.7 print('%d'%a) |
Output:
Conclusion
To conclude this tutorial, we discussed several methods to remove decimal places in Python. For this, we converted the float
type values to an integer using several methods. In the first method, we used the int
function to typecast the float value. Then we used the round()
function which rounded off the given value to the nearest integer.
We also demonstrated the use of functions from the math
library. These were the trunc()
, floor()
, and ceil()
functions. In the final method, we discussed how to use string formatting to remove decimal places in Python.
That’s all about how to remove decimals in Python.