ID : 491

viewed : 403

Tags : PythonPython Float

94

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.

`round()`

FunctionThe `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 `

`int()`

FunctionSuppose 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 `

`str()`

FunctionWe 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 `