[lang-ref] ( round_half_up ) ( python )

def test_round_half_up():
    # decimal.quantize
    from decimal import Decimal, ROUND_HALF_UP

    def round_half_up(x: str, ndigits: int = 0) -> Decimal:
        d = Decimal(x)
        q = Decimal("1").scaleb(-ndigits)  # ndigits=0 -> 1, ndigits=2 -> 0.01
        return d.quantize(q, rounding=ROUND_HALF_UP)

    assert round_half_up("1.5")  == Decimal("2")
    assert round_half_up("0.5")  == Decimal("1")
    assert round_half_up("-0.5") == Decimal("-1")
    assert round_half_up("-1.5") == Decimal("-2")