Skip to content

Commit 896c2ea

Browse files
authored
Cast number to Decimal in _get_compact_format (#930)
* fix rounding modes by using Decimal instead of float
1 parent eb647ba commit 896c2ea

File tree

1 file changed

+4
-2
lines changed

1 file changed

+4
-2
lines changed

babel/numbers.py

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -426,7 +426,7 @@ def format_compact_decimal(number, *, format_type="short", locale=LC_NUMERIC, fr
426426
>>> format_compact_decimal(12345, format_type="long", locale='en_US')
427427
u'12 thousand'
428428
>>> format_compact_decimal(12345, format_type="short", locale='en_US', fraction_digits=2)
429-
u'12.35K'
429+
u'12.34K'
430430
>>> format_compact_decimal(1234567, format_type="short", locale="ja_JP")
431431
u'123万'
432432
>>> format_compact_decimal(2345678, format_type="long", locale="mk")
@@ -454,6 +454,8 @@ def _get_compact_format(number, compact_format, locale, fraction_digits=0):
454454
The algorithm is described here:
455455
https://www.unicode.org/reports/tr35/tr35-45/tr35-numbers.html#Compact_Number_Formats.
456456
"""
457+
if not isinstance(number, decimal.Decimal):
458+
number = decimal.Decimal(str(number))
457459
format = None
458460
for magnitude in sorted([int(m) for m in compact_format["other"]], reverse=True):
459461
if abs(number) >= magnitude:
@@ -465,7 +467,7 @@ def _get_compact_format(number, compact_format, locale, fraction_digits=0):
465467
break
466468
# otherwise, we need to divide the number by the magnitude but remove zeros
467469
# equal to the number of 0's in the pattern minus 1
468-
number = number / (magnitude / (10 ** (pattern.count("0") - 1)))
470+
number = number / (magnitude // (10 ** (pattern.count("0") - 1)))
469471
# round to the number of fraction digits requested
470472
number = round(number, fraction_digits)
471473
# if the remaining number is singular, use the singular format

0 commit comments

Comments
 (0)