Kodeclik Blog
Python’s math.trunc() function
Python’s math.trunc() function takes one parameter, either an integer or a floating-point number, and simply returns the integer part of this argument without rounding up and down. This is useful when all you care about is the integer portion of the number but not really the closest whole number.
For example, if you pass in the value 7.8968 into the math.trunc() method, it will return 7 instead of 8. Similarly, if you pass in -3.987 into the math.trunc() method, it will return -3 instead of -4.
Let us try these operations by writing a simple program:
The output is:
When to use math.trunc()
There are several situations where you might consider using math.trunc(). Here is a simple example. Let us suppose we wish to test if a number is odd or even. We can simply divide the given number by 2, truncate it to an integer and see if it stays the same. If it stays the same, it means the number was wholly divisible by 2 to begin with and thus an integer.
The function is_even() below encapsulates this logic:
The output is:
as expected.
A different way to truncate is to use the integer casting operator int() which rounds down to find the integer portion of the argument. Unlike math.trunc(), int can also be used to convert numerical strings to integers. Consider for instance:
The output is:
As you can see int can take a string and interpret it in an integer context. It can also truncate a floating point number into an integer, like math.trunc() can. But math.trunc() cannot take a string as input as the error message shows.
To summarize, math.trunc() is a built-in function that allows us to easily truncate numbers by rounding down any given number to its integer component. In essence, this function removes all digits following the decimal point. Unlike rounding operations, the semantics of the math.trunc() function are the same whichever side of the integer value the argument falls on. In other words, truncating 3.1 vs 3.9 both yield 3 as the answer, not different answers because each is closer to a different integer.
For more Python content, checkout the math.ceil() and math.floor() functions! Also
learn about the math domain error in Python and how to fix it!
Interested in more things Python? Checkout our post on Python queues. Also see our blogpost on Python's enumerate() capability. Also if you like Python+math content, see our blogpost on Magic Squares. Finally, master the Python print function!
Want to learn Python with us? Sign up for 1:1 or small group classes.