How to localize number representations?

Hi all,

I'm trying to print numbers in their localized format (e.g. 1,000,000.00 for EN and 1.000.000,00 for DE)

Have successfully localized dates, using

if isinstance(value, date):
        value = value.isoformat()
        cell_value = i18nl10n.ulocalized_time(value
                                            , context=context
                                            , domain='plonelocales'
                                            , target_language=target_language)

Is there a similar utility to do this for numbers?

Looking at the zope.i18n API and trying to grok examples from tests gets me "almost there"... Ideally, I want to avoid specifying the thousands and decimal separators myself.

Cheers! - Norbert

1 Like

Almost too easy:

from Products.CMFPlone.interfaces import ILanguage
from zope.i18n.locales import locales
from decimal import Decimal

target_language = ILanguage(context).get_language()

if isinstance(value, (Decimal, float)):
    locale = locales.getLocale(target_language)
    formatter = locale.numbers.getFormatter('decimal')
    value = formatter.format(value)

You could also use Babel, which is a Python library that assists in localizing numbers, dates and currencies. Regarding localisation of numbers:

Good to know, thanks!