0
# Number and Currency Formatting
1
2
Locale-aware number, decimal, currency, and percentage formatting with support for different numbering systems, compact notation, and precision control. Babel's number formatting leverages CLDR data to provide culturally appropriate number representations.
3
4
## Capabilities
5
6
### Decimal Number Formatting
7
8
Format decimal numbers according to locale-specific conventions.
9
10
```python { .api }
11
def format_decimal(
12
number,
13
format=None,
14
locale=None,
15
decimal_quantization=True,
16
group_separator=True,
17
*,
18
numbering_system='latn'
19
):
20
"""
21
Format a decimal number according to locale conventions.
22
23
Args:
24
number (int|float|Decimal|str): Number to format
25
format (str|NumberPattern, optional): Number format pattern or None for default
26
locale (Locale|str, optional): Target locale
27
decimal_quantization (bool): Whether to quantize decimal precision
28
group_separator (bool): Whether to include group separators
29
numbering_system (str): Numbering system ('latn', 'arab', etc.)
30
31
Returns:
32
str: Formatted decimal number
33
"""
34
35
def format_number(number, locale=None):
36
"""
37
Format a number according to locale (alias for format_decimal).
38
39
Args:
40
number (int|float|Decimal): Number to format
41
locale (Locale|str): Target locale
42
43
Returns:
44
str: Formatted number
45
"""
46
```
47
48
Usage example:
49
50
```python
51
from babel.numbers import format_decimal, format_number
52
from babel import Locale
53
from decimal import Decimal
54
55
# Basic number formatting
56
print(format_number(1234.56, Locale('en_US'))) # "1,234.56"
57
print(format_number(1234.56, Locale('de_DE'))) # "1.234,56"
58
print(format_number(1234.56, Locale('fr_FR'))) # "1 234,56"
59
60
# High precision decimals
61
decimal_num = Decimal('123456.789123')
62
print(format_decimal(decimal_num, locale='en_US')) # "123,456.789123"
63
```
64
65
### Currency Formatting
66
67
Format currency amounts with locale-appropriate symbols and positioning.
68
69
```python { .api }
70
def format_currency(
71
number,
72
currency,
73
format=None,
74
locale=None,
75
currency_digits=True,
76
format_type='standard',
77
decimal_quantization=True,
78
group_separator=True,
79
*,
80
numbering_system='latn'
81
):
82
"""
83
Format a currency amount according to locale conventions.
84
85
Args:
86
number (int|float|Decimal|str): Amount to format
87
currency (str): Currency code (ISO 4217, e.g. 'USD', 'EUR')
88
format (str|NumberPattern, optional): Currency format pattern
89
locale (Locale|str, optional): Target locale
90
currency_digits (bool): Whether to use currency-specific decimal places
91
format_type (str): Format type ('standard', 'accounting', 'name')
92
decimal_quantization (bool): Whether to quantize to currency precision
93
group_separator (bool): Whether to include group separators
94
numbering_system (str): Numbering system
95
96
Returns:
97
str: Formatted currency amount
98
"""
99
```
100
101
Usage example:
102
103
```python
104
from babel.numbers import format_currency
105
from babel import Locale
106
107
amount = 1234.56
108
109
# Different locales and currencies
110
print(format_currency(amount, 'USD', locale='en_US')) # "$1,234.56"
111
print(format_currency(amount, 'EUR', locale='de_DE')) # "1.234,56 €"
112
print(format_currency(amount, 'JPY', locale='ja_JP')) # "¥1,235" (rounded to yen precision)
113
print(format_currency(amount, 'GBP', locale='en_GB')) # "£1,234.56"
114
115
# Accounting format (parentheses for negative)
116
print(format_currency(-123.45, 'USD', format_type='accounting', locale='en_US')) # "(123.45)"
117
```
118
119
### Percentage Formatting
120
121
Format percentages with appropriate symbols and decimal places.
122
123
```python { .api }
124
def format_percent(number, format=None, locale=None, numbering_system='latn'):
125
"""
126
Format a percentage according to locale conventions.
127
128
Args:
129
number (int|float|Decimal): Number to format as percentage (0.25 = 25%)
130
format (str, optional): Percent format pattern
131
locale (Locale|str): Target locale
132
numbering_system (str): Numbering system
133
134
Returns:
135
str: Formatted percentage
136
"""
137
```
138
139
Usage example:
140
141
```python
142
from babel.numbers import format_percent
143
144
print(format_percent(0.1234, locale='en_US')) # "12%"
145
print(format_percent(0.1234, locale='de_DE')) # "12 %"
146
print(format_percent(1.2345, locale='en_US')) # "123%"
147
```
148
149
### Scientific Notation
150
151
Format numbers in scientific notation according to locale conventions.
152
153
```python { .api }
154
def format_scientific(number, format=None, locale=None, numbering_system='latn'):
155
"""
156
Format a number in scientific notation.
157
158
Args:
159
number (int|float|Decimal): Number to format
160
format (str, optional): Scientific format pattern
161
locale (Locale|str): Target locale
162
numbering_system (str): Numbering system
163
164
Returns:
165
str: Number in scientific notation
166
"""
167
```
168
169
Usage example:
170
171
```python
172
from babel.numbers import format_scientific
173
174
print(format_scientific(1234567, locale='en_US')) # "1.234567E6"
175
print(format_scientific(0.000123, locale='en_US')) # "1.23E-4"
176
```
177
178
### Compact Number Formatting
179
180
Format numbers in compact notation (e.g., 1.2K, 1.5M) for display in limited space.
181
182
```python { .api }
183
def format_compact_decimal(number, format_type='short', fraction_digits=0,
184
locale=default_locale(), numbering_system="latn"):
185
"""
186
Format a number in compact notation.
187
188
Args:
189
number (int|float|Decimal): Number to format
190
format_type (str): Format type ('short', 'long')
191
fraction_digits (int): Number of fraction digits to display
192
locale (Locale|str): Target locale
193
numbering_system (str): Numbering system
194
195
Returns:
196
str: Compact formatted number
197
"""
198
199
def format_compact_currency(number, currency, format_type='short', fraction_digits=0,
200
locale=default_locale(), numbering_system="latn"):
201
"""
202
Format a currency amount in compact notation.
203
204
Args:
205
number (int|float|Decimal): Amount to format
206
currency (str): Currency code
207
format_type (str): Format type ('short', 'long')
208
fraction_digits (int): Number of fraction digits
209
locale (Locale|str): Target locale
210
numbering_system (str): Numbering system
211
212
Returns:
213
str: Compact formatted currency
214
"""
215
```
216
217
Usage example:
218
219
```python
220
from babel.numbers import format_compact_decimal, format_compact_currency
221
222
# Compact decimal formatting
223
print(format_compact_decimal(1234, locale='en_US')) # "1K"
224
print(format_compact_decimal(1234567, locale='en_US')) # "1M"
225
print(format_compact_decimal(1234, format_type='long', locale='en_US')) # "1 thousand"
226
227
# Compact currency formatting
228
print(format_compact_currency(1234567, 'USD', locale='en_US')) # "$1M"
229
```
230
231
### Currency Information Functions
232
233
Access currency-related metadata and validation.
234
235
```python { .api }
236
def list_currencies(locale=default_locale()):
237
"""
238
Get set of currency codes valid for locale.
239
240
Args:
241
locale (Locale|str): Target locale
242
243
Returns:
244
set[str]: Set of currency codes
245
"""
246
247
def validate_currency(currency, locale=default_locale()):
248
"""
249
Validate currency code for locale.
250
251
Args:
252
currency (str): Currency code to validate
253
locale (Locale|str): Target locale
254
255
Raises:
256
UnknownCurrencyError: If currency is invalid for locale
257
"""
258
259
def is_currency(currency, locale=default_locale()):
260
"""
261
Check if currency code is valid for locale.
262
263
Args:
264
currency (str): Currency code to check
265
locale (Locale|str): Target locale
266
267
Returns:
268
bool: True if currency is valid for locale
269
"""
270
271
def normalize_currency(currency, locale=default_locale()):
272
"""
273
Normalize currency code for locale.
274
275
Args:
276
currency (str): Currency code to normalize
277
locale (Locale|str): Target locale
278
279
Returns:
280
str|None: Normalized currency code or None if invalid
281
"""
282
283
def get_currency_name(currency, count=None, locale=default_locale()):
284
"""
285
Get display name for currency.
286
287
Args:
288
currency (str): Currency code
289
count (int|float, optional): Count for plural forms
290
locale (Locale|str): Target locale
291
292
Returns:
293
str: Currency display name
294
"""
295
296
def get_currency_symbol(currency, locale=default_locale()):
297
"""
298
Get currency symbol.
299
300
Args:
301
currency (str): Currency code
302
locale (Locale|str): Target locale
303
304
Returns:
305
str: Currency symbol
306
"""
307
308
def get_currency_precision(currency):
309
"""
310
Get default decimal precision for currency.
311
312
Args:
313
currency (str): Currency code
314
315
Returns:
316
int: Number of decimal places (e.g., 2 for USD, 0 for JPY)
317
"""
318
319
def get_currency_unit_pattern(currency, count=None, locale=default_locale()):
320
"""
321
Get currency unit pattern for count.
322
323
Args:
324
currency (str): Currency code
325
count (int|float, optional): Count for plural forms
326
locale (Locale|str): Target locale
327
328
Returns:
329
str: Currency unit pattern
330
"""
331
```
332
333
Usage example:
334
335
```python
336
from babel.numbers import (get_currency_name, get_currency_symbol,
337
get_currency_precision, is_currency)
338
339
print(get_currency_name('USD', locale='en_US')) # "US Dollar"
340
print(get_currency_symbol('USD', locale='en_US')) # "$"
341
print(get_currency_precision('USD')) # 2
342
print(get_currency_precision('JPY')) # 0
343
print(is_currency('USD', locale='en_US')) # True
344
```
345
346
### Territory Currency Information
347
348
Get currencies used in specific territories/countries.
349
350
```python { .api }
351
def get_territory_currencies(territory, start_date=None, end_date=None,
352
tender=True, non_tender=False, include_details=False):
353
"""
354
Get currencies used in territory.
355
356
Args:
357
territory (str): Territory code (e.g. 'US', 'DE')
358
start_date (datetime.date, optional): Start date filter
359
end_date (datetime.date, optional): End date filter
360
tender (bool): Include legal tender currencies
361
non_tender (bool): Include non-tender currencies
362
include_details (bool): Include detailed currency information
363
364
Returns:
365
list|dict: Currency codes or detailed currency information
366
"""
367
```
368
369
### Number Symbol Access
370
371
Get locale-specific number formatting symbols.
372
373
```python { .api }
374
def get_decimal_symbol(locale=default_locale(), numbering_system="latn"):
375
"""
376
Get decimal separator symbol.
377
378
Args:
379
locale (Locale|str): Target locale
380
numbering_system (str): Numbering system
381
382
Returns:
383
str: Decimal separator (e.g., "." or ",")
384
"""
385
386
def get_group_symbol(locale=default_locale(), numbering_system="latn"):
387
"""
388
Get thousands separator symbol.
389
390
Args:
391
locale (Locale|str): Target locale
392
numbering_system (str): Numbering system
393
394
Returns:
395
str: Group separator (e.g., "," or "." or " ")
396
"""
397
398
def get_plus_sign_symbol(locale=default_locale(), numbering_system="latn"):
399
"""
400
Get plus sign symbol.
401
402
Args:
403
locale (Locale|str): Target locale
404
numbering_system (str): Numbering system
405
406
Returns:
407
str: Plus sign symbol
408
"""
409
410
def get_minus_sign_symbol(locale=default_locale(), numbering_system="latn"):
411
"""
412
Get minus sign symbol.
413
414
Args:
415
locale (Locale|str): Target locale
416
numbering_system (str): Numbering system
417
418
Returns:
419
str: Minus sign symbol
420
"""
421
422
def get_exponential_symbol(locale=default_locale(), numbering_system="latn"):
423
"""
424
Get exponential notation symbol.
425
426
Args:
427
locale (Locale|str): Target locale
428
numbering_system (str): Numbering system
429
430
Returns:
431
str: Exponential symbol (e.g., "E")
432
"""
433
434
def get_infinity_symbol(locale=default_locale(), numbering_system="latn"):
435
"""
436
Get infinity symbol.
437
438
Args:
439
locale (Locale|str): Target locale
440
numbering_system (str): Numbering system
441
442
Returns:
443
str: Infinity symbol (e.g., "∞")
444
"""
445
```
446
447
### Number Parsing
448
449
Parse formatted number strings back to numeric values.
450
451
```python { .api }
452
def parse_number(string, locale=default_locale()):
453
"""
454
Parse a formatted number string.
455
456
Args:
457
string (str): Formatted number string
458
locale (Locale|str): Source locale for parsing
459
460
Returns:
461
int|float: Parsed numeric value
462
463
Raises:
464
NumberFormatError: If parsing fails
465
"""
466
467
def parse_decimal(string, locale=default_locale(), strict=False):
468
"""
469
Parse a formatted decimal string.
470
471
Args:
472
string (str): Formatted decimal string
473
locale (Locale|str): Source locale for parsing
474
strict (bool): Whether to use strict parsing
475
476
Returns:
477
Decimal: Parsed decimal value
478
479
Raises:
480
NumberFormatError: If parsing fails
481
"""
482
```
483
484
### Decimal Precision Utilities
485
486
Utilities for working with decimal precision and quantization.
487
488
```python { .api }
489
def get_decimal_precision(number):
490
"""
491
Get precision of a decimal number.
492
493
Args:
494
number (Decimal): Decimal number
495
496
Returns:
497
int: Number of decimal places
498
"""
499
500
def get_decimal_quantum(precision):
501
"""
502
Get quantum for decimal precision.
503
504
Args:
505
precision (int|Decimal): Precision value
506
507
Returns:
508
Decimal: Quantum for the precision
509
"""
510
```
511
512
### Number Pattern Parsing
513
514
Parse and work with number format patterns.
515
516
```python { .api }
517
def parse_pattern(pattern):
518
"""
519
Parse a number format pattern.
520
521
Args:
522
pattern (str): Number format pattern
523
524
Returns:
525
NumberPattern: Parsed pattern object
526
"""
527
528
def parse_grouping(pattern):
529
"""
530
Parse grouping information from pattern.
531
532
Args:
533
pattern (str): Number format pattern
534
535
Returns:
536
tuple[int, int]: Primary and secondary grouping sizes
537
"""
538
539
class NumberPattern:
540
"""
541
Represents a parsed number format pattern.
542
"""
543
def apply(self, value, locale, currency=None, numbering_system="latn",
544
decimal_quantization=True, group_separator=True):
545
"""
546
Apply this pattern to format a number.
547
548
Args:
549
value (int|float|Decimal): Number to format
550
locale (Locale|str): Target locale
551
currency (str, optional): Currency code for currency patterns
552
numbering_system (str): Numbering system
553
decimal_quantization (bool): Whether to quantize decimals
554
group_separator (bool): Whether to include group separators
555
556
Returns:
557
str: Formatted number
558
"""
559
```
560
561
## Exception Classes
562
563
```python { .api }
564
class UnknownCurrencyError(Exception):
565
"""Raised when an unknown currency code is used."""
566
567
class UnsupportedNumberingSystemError(Exception):
568
"""Raised when an unsupported numbering system is used."""
569
570
class UnknownCurrencyFormatError(Exception):
571
"""Raised when an unknown currency format type is used."""
572
573
class NumberFormatError(Exception):
574
"""Raised when number formatting or parsing fails."""
575
```
576
577
## Constants
578
579
```python { .api }
580
LC_NUMERIC: str
581
"""Default numeric locale category constant."""
582
```