Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
49 lines
1.5 KiB
Python
49 lines
1.5 KiB
Python
"""Decimal rounding helpers."""
|
|
|
|
from __future__ import annotations
|
|
|
|
from decimal import (
|
|
ROUND_CEILING,
|
|
ROUND_DOWN,
|
|
ROUND_FLOOR,
|
|
ROUND_HALF_EVEN,
|
|
ROUND_HALF_UP,
|
|
ROUND_UP,
|
|
Decimal,
|
|
)
|
|
|
|
_MODES = {
|
|
"half_up": ROUND_HALF_UP,
|
|
"down": ROUND_DOWN,
|
|
"up": ROUND_UP,
|
|
"floor": ROUND_FLOOR,
|
|
"ceiling": ROUND_CEILING,
|
|
}
|
|
|
|
|
|
def quantum(places: int) -> Decimal:
|
|
"""The Decimal with ``places`` decimal places, e.g. ``quantum(2) == Decimal('0.01')``."""
|
|
return Decimal(1).scaleb(-places)
|
|
|
|
|
|
def round_half_even(value: Decimal, places: int = 2) -> Decimal:
|
|
"""Banker's rounding: ties go to the neighbour whose last digit is even."""
|
|
return value.quantize(quantum(places), rounding=ROUND_HALF_EVEN)
|
|
|
|
|
|
def round_decimal(value: Decimal, places: int = 2, mode: str = "half_even") -> Decimal:
|
|
"""Round ``value`` to ``places`` decimal places using a named rounding mode."""
|
|
if mode == "half_even":
|
|
return round_half_even(value, places)
|
|
if mode not in _MODES:
|
|
raise ValueError("unknown rounding mode: %s" % mode)
|
|
return value.quantize(quantum(places), rounding=_MODES[mode])
|
|
|
|
|
|
def round_to_increment(value: Decimal, increment: Decimal, mode: str = "half_even") -> Decimal:
|
|
"""Round to a multiple of ``increment`` (for example 0.05 for cash rounding)."""
|
|
if increment <= 0:
|
|
raise ValueError("increment must be positive")
|
|
steps = round_decimal(value / increment, 0, mode)
|
|
return steps * increment
|