How to Remove Decimals in Python

Quick Solution
To Remove decimals in Python, use int() function.

Or use math.trunc()

Output

3

Please 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,

Output

2

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.

Output:

2

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,

2
3

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.

Output:

2

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.

Was this post helpful?

Leave a Reply

Your email address will not be published. Required fields are marked *