Truncate in Python
There are many built-in modules in python. Out of these module there is one interesting module known as math module which have several functions in it like, ceil, floor, truncate, factorial, fabs, etc.
Out of these functions there is an interesting function called truncate which behaves as a ceiling function for negative number and floor function for positive number.
Time Complexity: O(1)
Auxiliary Space: O(1)
Python3
import math
print (math.floor( 3.5 ))
print (math.trunc( 3.5 ))
print (math.ceil( 3.5 ))
|
Output:
3.0
3
4.0
In case of negative number
Python3
import math
print (math.floor( - 3.5 ))
print (math.trunc( - 3.5 ))
print (math.ceil( - 3.5 ))
|
Output:
-4.0
-3
-3.0
This is because the ceiling function is used to round up, i.e., towards positive infinity and floor function is used to round down, i.e., towards negative infinity.
But the truncate function is used to round up or down towards zero.
Diagrammatic representation of truncate function:-
Last Updated :
20 Feb, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...