Complete guide to all Python rounding methods with practical examples
Python provides multiple built-in methods for rounding numbers, each serving different purposes. This comprehensive guide covers all the essential rounding functions in Python, from the basic round() function to advanced techniques using the math and decimal modules.
Whether you're working on data science projects, financial calculations, or general number formatting, understanding Python's rounding methods is essential for accurate and predictable results.
round(number, ndigits=None)The most common rounding method in Python. Rounds a number to a specified precision in decimal digits. Uses banker's rounding (round half to even) by default.
# Round to nearest integer print(round(3.14159)) # Output: 3 print(round(3.7)) # Output: 4 print(round(-2.5)) # Output: -2 (banker's rounding) # Round to decimal places print(round(3.14159, 2)) # Output: 3.14 print(round(12.567, 1)) # Output: 12.6 print(round(0.666, 2)) # Output: 0.67 # Round to left of decimal point print(round(1234.56, 0)) # Output: 1235.0 print(round(1234, -1)) # Output: 1230 print(round(1234, -2)) # Output: 1200 print(round(1234, -3)) # Output: 1000
Python's round() uses "round half to even" (banker's rounding). When a number is exactly halfway between two values, it rounds to the nearest EVEN number:
print(round(0.5)) # Output: 0 (rounds to even) print(round(1.5)) # Output: 2 (rounds to even) print(round(2.5)) # Output: 2 (rounds to even) print(round(3.5)) # Output: 4 (rounds to even)
math.ceil(x)Returns the ceiling of x, the smallest integer greater than or equal to x. Always rounds UP toward positive infinity.
import math # Positive numbers - always round up print(math.ceil(3.1)) # Output: 4 print(math.ceil(3.9)) # Output: 4 print(math.ceil(3.0)) # Output: 3 (already integer) # Negative numbers - toward positive infinity print(math.ceil(-3.1)) # Output: -3 print(math.ceil(-3.9)) # Output: -3 # Zero print(math.ceil(0.1)) # Output: 1 print(math.ceil(-0.1)) # Output: 0
import math
# Calculate pages needed for items
items = 47
items_per_page = 10
pages_needed = math.ceil(items / items_per_page)
print(f"Pages needed: {pages_needed}") # Output: 5
# Round up payment to nearest dollar
amount = 12.03
rounded_up = math.ceil(amount)
print(f"Rounded up: {rounded_up}") # Output: 13
# Calculate minimum boxes needed
total_items = 127
box_capacity = 25
boxes = math.ceil(total_items / box_capacity)
print(f"Boxes needed: {boxes}") # Output: 6math.floor(x)Returns the floor of x, the largest integer less than or equal to x. Always rounds DOWN toward negative infinity.
import math # Positive numbers - always round down print(math.floor(3.9)) # Output: 3 print(math.floor(3.1)) # Output: 3 print(math.floor(3.0)) # Output: 3 # Negative numbers - toward negative infinity print(math.floor(-3.1)) # Output: -4 print(math.floor(-3.9)) # Output: -4 # Zero print(math.floor(0.9)) # Output: 0 print(math.floor(-0.1)) # Output: -1
import math
# Array indexing (ensure valid index)
position = 7.8
index = math.floor(position)
print(f"Array index: {index}") # Output: 7
# Floor division alternative
total = 47
per_group = 10
groups = math.floor(total / per_group)
print(f"Complete groups: {groups}") # Output: 4
# Discount calculation (round down)
price = 99.99
discount_rate = 0.15
discount = math.floor(price * discount_rate)
print(f"Discount: {discount}") # Output: 14math.trunc(x)Returns the truncated integer value by removing the decimal part. Always rounds TOWARD ZERO, regardless of positive or negative.
import math # Positive numbers - remove decimal print(math.trunc(3.9)) # Output: 3 print(math.trunc(3.1)) # Output: 3 # Negative numbers - remove decimal (toward zero) print(math.trunc(-3.1)) # Output: -3 print(math.trunc(-3.9)) # Output: -3 # Compare to floor print(math.floor(-3.9)) # Output: -4 (toward -∞) print(math.trunc(-3.9)) # Output: -3 (toward 0)
| Method | 3.7 | -3.7 | 2.5 | Direction |
|---|---|---|---|---|
| round() | 4 | -4 | 2 | Nearest (banker's) |
| math.ceil() | 4 | -3 | 3 | Toward +∞ |
| math.floor() | 3 | -4 | 2 | Toward -∞ |
| math.trunc() | 3 | -3 | 2 | Toward 0 |
Floating-point arithmetic can lead to unexpected rounding results:
# Problem print(round(2.675, 2)) # Output: 2.67 (expected 2.68!) # Reason: 2.675 is actually stored as 2.674999999...
Solution: Use Decimal module for precision
from decimal import Decimal, ROUND_HALF_UP
num = Decimal('2.675')
result = num.quantize(Decimal('0.01'), ROUND_HALF_UP)
print(result) # Output: 2.68Python's round() doesn't always round 0.5 up:
# Problem - inconsistent .5 rounding print(round(0.5)) # Output: 0 print(round(1.5)) # Output: 2 print(round(2.5)) # Output: 2
Solution: Use Decimal with ROUND_HALF_UP
from decimal import Decimal, ROUND_HALF_UP
def traditional_round(num, decimals=0):
d = Decimal(str(num))
return float(d.quantize(Decimal(10) ** -decimals, ROUND_HALF_UP))
print(traditional_round(0.5)) # Output: 1.0
print(traditional_round(1.5)) # Output: 2.0
print(traditional_round(2.5)) # Output: 3.0import pandas as pd
import numpy as np
# Round all numeric columns to 2 decimals
df = pd.DataFrame({
'price': [12.456, 23.789, 45.123],
'tax': [1.0567, 2.0234, 3.8901]
})
df_rounded = df.round(2)
print(df_rounded)
# Output:
# price tax
# 0 12.46 1.06
# 1 23.79 2.02
# 2 45.12 3.89from decimal import Decimal, ROUND_HALF_UP
def calculate_total(price, tax_rate, quantity):
"""Calculate order total with proper rounding"""
price_d = Decimal(str(price))
tax_d = Decimal(str(tax_rate))
qty_d = Decimal(str(quantity))
subtotal = price_d * qty_d
tax = subtotal * tax_d
total = subtotal + tax
# Round to 2 decimal places (cents)
return float(total.quantize(Decimal('0.01'), ROUND_HALF_UP))
total = calculate_total(19.99, 0.085, 3)
print(f"Total: ${total}") # Output: Total: $65.07def format_percentage(value, decimals=1):
"""Format value as percentage with rounding"""
percentage = round(value * 100, decimals)
return f"{percentage}%"
def format_currency(value):
"""Format value as currency"""
return f"${value:,.2f}"
# Examples
print(format_percentage(0.1567, 2)) # Output: 15.67%
print(format_currency(1234567.89)) # Output: $1,234,567.89Always use the Decimal module with ROUND_HALF_UP for money to avoid floating-point errors.
Use round() for general purposes, ceil() for safety margins, floor() for conservative estimates, and trunc() when you need to remove decimals.
Remember that Python's round() uses banker's rounding by default. Use Decimal if you need traditional rounding.
Always test with negative numbers, zeros, and exact halfway values (like 2.5) to ensure expected behavior.
Complete overview of Python's rounding ecosystem and best practices
Detailed guide to math.floor() and rounding down techniques
Specific guide for rounding to 2 decimal places
General Python rounding guide with NumPy examples
Learn JavaScript rounding techniques
Complete Java rounding guide with BigDecimal