]> git.ipfire.org Git - thirdparty/babel.git/commitdiff
feat: Add `Format.compact_decimal` utility (#921)
authorJonah Lawrence <jonah@freshidea.com>
Wed, 2 Nov 2022 06:35:41 +0000 (00:35 -0600)
committerGitHub <noreply@github.com>
Wed, 2 Nov 2022 06:35:41 +0000 (08:35 +0200)
babel/support.py
tests/test_support.py

index 80e93400d392be0e1712ec70617389ee736dfae5..3efc0036ba356cbd2253c8fe1f15f5091ca937c4 100644 (file)
@@ -18,7 +18,7 @@ from babel.core import Locale
 from babel.dates import format_date, format_datetime, format_time, \
     format_timedelta
 from babel.numbers import format_decimal, format_currency, \
-    format_percent, format_scientific
+    format_percent, format_scientific, format_compact_decimal
 
 
 class Format:
@@ -108,6 +108,17 @@ class Format:
         """
         return format_decimal(number, format, locale=self.locale)
 
+    def compact_decimal(self, number, format_type='short', fraction_digits=0):
+        """Return a number formatted in compact form for the locale.
+
+        >>> fmt = Format('en_US')
+        >>> fmt.compact_decimal(123456789)
+        u'123M'
+        """
+        return format_compact_decimal(number, format_type=format_type,
+                                      fraction_digits=fraction_digits,
+                                      locale=self.locale)
+
     def currency(self, number, currency):
         """Return a number in the given currency formatted for the locale.
         """
index 2d8e9332d88d0d87a0d87142def69ad6ce9a3361..93ad37e4a62ece078c27ab41a5a3c9f621f55557 100644 (file)
@@ -329,6 +329,11 @@ def test_format_decimal():
     assert fmt.decimal(1.2345) == '1.234'
 
 
+def test_format_compact_decimal():
+    fmt = support.Format('en_US')
+    assert fmt.compact_decimal(1234567, format_type='long', fraction_digits=2) == '1.23 million'
+
+
 def test_format_percent():
     fmt = support.Format('en_US')
     assert fmt.percent(0.34) == '34%'