Format numbers as currency in Python

后端 未结 2 1757
攒了一身酷
攒了一身酷 2020-12-31 13:05

I learn from Currency formatting in Python, use the locale module to format numbers as currency. For instance,

#! /usr/bin/env python
# -*- coding: utf-8 -*-         


        
相关标签:
2条回答
  • 2020-12-31 13:08

    For reference (for those that are looking to format numbers similar to how you would format currency), you can use locale.format_string to format numbers

    value = 123456789
    
    import locale
    locale.setlocale(locale.LC_ALL, 'de_DE') 
    print(locale.format_string('%.2f', value, True))
    

    Would return

    123.456.789,00
    
    0 讨论(0)
  • 2020-12-31 13:12

    babel.numbers

    In [22]: from babel.numbers import format_decimal
    In [23]:  format_decimal(12345, locale='de_DE')
    Out[23]: u'12.345'
    
    In [24]: format_decimal(1.2345, locale='sv_SE')
    Out[24]: u'1,234'
    

    Or in your case format_currency:

    In [7]: from babel.numbers import format_currency
    
    In [8]: print format_currency(1099.98, 'USD', locale='en_US')
    $1,099.98
    
    In [9]: print format_currency(1099.98, 'USD', locale='es_CO')
    1.099,98 US$
    
    In [10]: print format_currency(1099.98, 'EUR', locale='de_DE')
    1.099,98 €
    
    0 讨论(0)
提交回复
热议问题