In this lesson, you will learn how to manipulate decimal numbers by choosing between rounding strategies and truncation methods.
When working with floating-point numbers, you often need to convert them into whole integers. Python provides several ways to do this, and understanding the difference between them is vital for accurate calculations.
Rounding Ties-to-Even
Python’s built-in round() function uses a strategy called "rounding to the nearest even number." When a number is exactly halfway between two integers (like 2.5 or 3.5), it rounds to the nearest even integer.
round(2.5)becomes2round(3.5)becomes4
This helps reduce statistical bias in long lists of calculations because it doesn't always round up.
Floor, Ceil, and Trunc
To perform more predictable changes, we look to the math module:
math.floor(): Always rounds "down," moving toward negative infinity. It tells you the greatest integer less than or equal to the number.math.ceil(): Always rounds "up," moving toward positive infinity. It tells you the smallest integer greater than or equal to the number.math.trunc(): Simply chops off the decimal part, effectively moving toward zero.
import math
# Comparison of behavior for 2.5
print(round(2.5)) # Result: 2 (Ties-to-even)
print(math.floor(2.5)) # Result: 2
print(math.ceil(2.5)) # Result: 3
print(math.trunc(2.5)) # Result: 2
# Comparison of behavior for -2.5
print(round(-2.5)) # Result: -2
print(math.floor(-2.5)) # Result: -3
print(math.ceil(-2.5)) # Result: -2
print(math.trunc(-2.5)) # Result: -2
Display vs. Calculation
It is important to remember that these functions change the numeric value of the data. If you only want to change how a number looks on the screen (such as showing two decimal places in a string), that is a formatting concern, not a mathematical operation. The functions above change the underlying integer object itself.
Key Takeaway: Use round() for statistical fairness, floor() and ceil() for directional boundaries, and trunc() to simply discard fractional information.