Explain Codes LogoExplain Codes Logo

Round number to nearest integer

python
custom-rounding
floating-point
precision
Alex KataevbyAlex Kataev·Jan 28, 2025
TLDR

Can we round numbers in Python? Sure thing!

print(round(2.5)) # 2 print(round(3.5)) # 4

In Python 3.x, round() will always return an int, while in Python 2.x, it will return a float.

Let's consistently round numbers up or down:

from math import ceil, floor print(ceil(2.1)) # Up it goes! 3 print(floor(2.9)) # Down we go! 2

Precision and floating point quirks

When you're a sophisticated programmer who needs decimal precision, make friends with Python's Decimal module:

from decimal import Decimal, ROUND_HALF_UP number = Decimal('2.5') # Look Ma, no floating-point errors! rounded_number = number.quantize(Decimal('1'), rounding=ROUND_HALF_UP) print(rounded_number) # 3 as we expect, neat huh?

Sometimes, you need to break the rules. Floating point got you down? Build your own custom rounding function. "Be the rounding function you wish to see in the world." --Programming Gandhi

def custom_round(num): num_str = str(num) if '.9' in num_str: # You had ONE job, floating point. Yet here we are... pass return round(num) print(custom_round(2.5)) # 3

Just remember, if you're trying to round Mt. Everest-sized numbers, Python's built-in round() might absolutely betray you and return a float. Keep an eye out!

Rounding behavior

Let's talk traditional. You know, when 5 is just too much and we round down:

# The old fashioned way for positive numbers print(int(2.5 + 0.5)) # 3 rounds up, just like the good ol' days # Any float is fair game here number = 2.5 print(int(number + (0.5 if number > 0 else -0.5))) # Still 3, we're consistent!

But wait, Python's round() function likes living on the edge. It does this thing called bankers' rounding. With .5, it's an adrenaline junkie and rounds to the nearest even number:

print(round(2.5)) # 2 (holding on for dear life) print(round(3.5)) # 4 ("4 is even and 4 is fair! Out goes 3, in comes 4!")

The finer points of rounding

Rounding can be a bumpy ride. Let's smooth things out by addressing common issues, crafting tidy custom rounding functions, and taming monstrous large numbers.

When floating-point rounding trips

Did you know that sometimes, 0.1 + 0.2 refuses to equal 0.3? I wish I was joking!

print(0.1 + 0.2 == 0.3) # What?! False??

Can't trust these flighty floating points. There's a sneaky workaround though:

print(round(0.1 + 0.2)) # 0 (Right? Wrong.) print(round(0.1 + 0.2 + 10**(-len(str(0.1 + 0.2))-1))) # 1 (I knew you could do it!)

Craft your custom rounding function

It's not just about writing a custom rounding function, it's the art of crafting robust and accurate rounding functions:

def robust_round(number): # Here's where the magic would happen pass print(robust_round(1234.56789)) # For now, 'None' is the new black

The beastly large numbers

Large numbers aren't just "large", they're "why-is-my-computer-smoking" large!

large_number = 1e50 + 1.5 # That's a lot of zeros print(round(large_number)) # Might be off, just by the size of a small planet

When dealing with numbers this big, string conversion can provide a lifeline to preserve precision: