Format numbers as currency in Python

后端 未结 2 1774
攒了一身酷
攒了一身酷 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: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 €
    

提交回复
热议问题