How to Truncate a Float in Python

In this tutorial, we will learn about the process by which we can truncate a float in Python. In python, we can truncate float to certain decimal places and can also truncate to no decimal places. We can do this in various processes either by using the int() function or math library and other ways too.

There are several benefits of truncating a float in python such as can represent output in a more attractive and presentation-ready way, making the output more user-friendly and easy to look at.

Using math library to truncate a float

math library in python has a library that can be used to truncate a float. We use the trunk() function for truncating a float. In the code given below, we are using the math library:

It can be seen in the output that after printing the math.trunc() value, the float value is truncated to integer value.

# Truncate a float in python
import math
float_1 = 12.35
float_2 = -5684.545

print(math.trunc(float_1))
print(math.trunc(float_2))
Output

12

-5684

Using the int() function to truncate a float

We can also use the int() function to truncate a float in python. The syntax is mostly the same as discussed for the math library. The int() function truncate a float in python as it takes float value and converts it into an integer. It truncates a float by removing the decimal places.

Below is the program for int() function:

float_1 = 12.35
float_2 = -5684.545

print(int(float_1))
print(int(float_2))
Output:

12

-5684

Using String methods to truncate a float

String methods are also used to truncate a float in python. So we first convert the float in string and then remove the decimals places. We can split the string using str. split() and can take only the first split’s section.

Below is the code for string methods to truncate a float:

# Truncate a float using str.split()

float_1 = 12.35
float_2 = -5684.545

print(str(float_1).split('.')[0])
print(str(float_2).split('.')[0])
Output:

12

-5684

Leave a Reply

Your email address will not be published.