math.trunc() vs. math.floor() in Python

Python provides a variety of mathematical functions to handle numerical operations. Two such functions, math.trunc() and math.floor(), may seem similar at first glance, but they serve distinct purposes when rounding numbers. Both functions accept a single argument, x, which can be either a floating-point number or an integer. They both return an integer value, making them versatile tools in numerical computations. In this Answer, we’ll study these functions and explore when to use them.

The math.trunc() function

The math.trunc() function is used to truncate a number, effectively removing the decimal part without performing any rounding. It essentially rounds toward zero, giving us the integer portion of a number.

import math
x = 3.8
y = -2.3
result_x = math.trunc(x) # Output: 3
result_y = math.trunc(y) # Output: -2
print(result_x)
print(result_y)

The math.floor() function

On the other hand, math.floor() returns the largest integer that is less than or equal to a given number. It always rounds down, even for negative numbers.

import math
x = 3.8
y = -2.3
result_x = math.floor(x) # Output: 3
result_y = math.floor(y) # Output: -3
print(result_x)
print(result_y)

Differences

The key distinction between these functions lies in how they handle negative numbers. While math.floor() consistently rounds down (towards negative infinity), math.trunc() effectively truncates towards zero. Let's look at the key difference between these two with the help of an illustration:

math.trunc() vs. math.floor()
math.trunc() vs. math.floor()

Let's understand this with the help of coding examples:

import math
x = -0.2
result_floor = math.floor(x) # Output: -1
result_trunc = math.trunc(x) # Output: 0
print("Result of floor:", result_floor)
print("Result of trunc:", result_trunc)

In this case, math.floor() yields 3-3, as it rounds down to the nearest integer (which is less than or equal to 2.7-2.7). On the other hand, math.trunc() simply truncates towards zero, giving 2-2.

Choosing the right function

Choosing between math.trunc() and math.floor() depends on our specific use case. If we need to ensure that the result is always rounded down, even for negative numbers, math.floor() is the appropriate choice. Conversely, if we want to truncate towards zero, we’ll use math.trunc().

In summary, math.trunc() and math.floor() are valuable tools for handling numerical operations in Python. Understanding their behavior, particularly when dealing with negative numbers, empowers us to make informed decisions in our code. By leveraging these functions effectively, we can achieve precise and accurate results in our mathematical computations.

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved