Contents
Python math.trunc()
math.trunc(x) function truncates the decimal value and returns the real or integral value of x.
Syntax
The syntax to call trunc() function is
math.trunc(x)
where
Parameter | Required | Description |
---|---|---|
x | Yes | A numeric value. |
If x is infinity, then trunc(x) raises OverflowError.
If x is nan, then trunc(x) raises ValueError.
Examples
Truncate x = 3.1415 using math.trunc().
Python Program
import math
x = 3.1415
result = math.trunc(x)
print('trunc(x) :', result)
Run Output
trunc(x) : 3
Truncate negative value, x = -3.1415, using math.trunc().
Python Program
import math
x = -3.1415
result = math.trunc(x)
print('trunc(x) :', result)
Run Output
trunc(x) : -3
Truncate x = infinity.
Python Program
import math
x = math.inf
result = math.trunc(x)
print('trunc(x) :', result)
Run Output
OverflowError: cannot convert float infinity to integer
Truncate an integer.
Python Program
import math
x = 3
result = math.trunc(x)
print('trunc(x) :', result)
Run Output
trunc(x) : 3
Truncate x = NaN.
Python Program
import math
x = math.nan
result = math.trunc(x)
print('trunc(x) :', result)
Run Output
ValueError: cannot convert float NaN to integer
Summary
In this Python Examples tutorial, we learned the syntax of, and examples for math.trunc() function.