Truncate Float in Python

Truncate Float in Python

Syed Moiz Haider Mar-21, 2021 Feb-26, 2021 Python Python Float
  1. Truncate a Float in Python Using the round() Function
  2. Truncate a Float in Python Using the int() Function
  3. Truncate a Float in Python Using the str() Function

This tutorial will explain various methods to truncate a float in Python. The float truncation is used to make the calculation easier. We can truncate a float by either dropping the remaining digits or rounding it. We will look into both methods in this tutorial.

Truncate a Float in Python Using the round() Function

The round(number, n) function takes a number as input and rounds it to n decimal places.

In case we want to truncate the float by rounding it, we can do so by using the round() function in Python. The below example code demonstrates how to use the round() function to truncate a float.

print(round(1923334567124,4))
print(round(2345.1252342,4))
print(round(192.67,4))

Output:

1923334567124
2345.1252
192.67

Truncate a Float in Python Using the int() Function

Suppose we want to truncate a float by merely dropping the remaining digits after n decimal places. We can do so by first multiplying the float with the 10**n where n the number of digits of the float we want to keep after the decimal. Then, convert it into an integer and divide it with the same 10**n value. We can then convert it back into a float.

The below example code demonstrates how to truncate a float by dropping the remaining digit using the int() function in Python.

def truncate(num, n):
    integer = int(num * (10**n))/(10**n)
    return float(integer)

print(truncate(1923334567124,4))
print(truncate(2345.1252342,4))
print(truncate(192.67,4))

Output:

1923334567124.0
2345.1252
192.6699

Truncate a Float in Python Using the str() Function

We can also truncate a float by dropping the remaining digits after n decimal places by first converting it into a string.

Once we convert the float into a string, we can look for the decimal point . in the string; if it exists, we can keep the n digits after it or complete float if it has less than n digits after the decimal point.

The below example code demonstrates how to use the str() function to truncate a float in Python.

def truncate(num,n):
    temp = str(num)
    for x in range(len(temp)):
        if temp[x] == '.':
            try:
                return float(temp[:x+n+1])
            except:
                return float(temp)      
    return float(temp)

print(truncate(1923334567124,4))
print(truncate(2345.1252342,4))
print(truncate(192.67,4))

Output:

1923334567124.0
2345.1252
192.67

Related Article - Python Float

  • Find Maximum Float Value in Python
  • Fix Float Object Is Not Callable in Python
  • Convert a String to a Float Value in Python
  • Check if a String Is a Number in Python
  • Convert String to Decimal in Python
  • Convert List to Float in Python