babel icon indicating copy to clipboard operation
babel copied to clipboard

Wrong rounding when using decimal.ROUND_CEILING

Open Niklas2501 opened this issue 1 year ago • 0 comments

Overview Description

Formatting a negative number with the rounding mode decimal.ROUND_CEILING yields a wrong result.

Steps to Reproduce

from babel.numbers import decimal, format_decimal

with decimal.localcontext(decimal.Context(rounding=decimal.ROUND_CEILING)):
    x = -100.75
    x_formatted = format_decimal(x, format="#")

    # For comparison: Round with the decimal class directly
    x_decimal = decimal.Decimal(x)
    x_decimal_rounded = round(x_decimal, 0)
    
print(x_formatted, x_decimal_rounded)
# -101 -100

Actual Results

"-101"

Expected Results

"-100"

Additional Information

The issue, as far as I could understand the problem in the Babel code, is that only a flag is set for a negative number in order to add it again at the end of processing. With this rounding rule, however, this must be taken into account. Currently in NumberPattern._quantize_value() -100.75 is rounded in the same way as 100.75, which gives 101 as the result. However, for -100.75 this corresponds to the rounding rule decimal.ROUND_UP, not decimal.ROUND_CEILING.

Niklas2501 avatar Jul 08 '24 13:07 Niklas2501