Skip to content

Instantly share code, notes, and snippets.

@peteristhegreat
Created March 23, 2026 01:42
Show Gist options
  • Select an option

  • Save peteristhegreat/9e09055a24aa99b6af9f135d79d02114 to your computer and use it in GitHub Desktop.

Select an option

Save peteristhegreat/9e09055a24aa99b6af9f135d79d02114 to your computer and use it in GitHub Desktop.
Banker's Rounding v. Rounding I was taught in School

https://stackoverflow.com/questions/10825926/why-does-python-3-round-half-to-even

WHAT! Python changed how rounding worked!?!?

https://chem.academy/notes/bankers-rounding.html

This article lays it out how I would think it would...

https://cplusplus.com/articles/1UCRko23/

To achieve textbook math rounding:

floor(x + 0.5)

Otherwise, many languages choose to use Banker's Rounding aka "round half to even".

import math

def bankers_round(value: float, decimals: int = 0) -> float:
    factor = 10 ** decimals
    shifted = value * factor
    floored = math.floor(shifted)
    diff = shifted - floored  # fractional part

    if diff < 0.5:
        result = floored
    elif diff > 0.5:
        result = floored + 1
    else:
        # Exactly 0.5 — round to nearest even
        result = floored if floored % 2 == 0 else floored + 1

    return result / factor

or much more simply:

round(x)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment