mtrebron
(Norbert )
October 9, 2018, 2:35pm
1
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 https://github.com/plone/Products.CMFPlone/blob/master/Products/CMFPlone/i18nl10n.py
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.
https://docs.zope.org/zope.i18n/api.html
self.assertEqual(self.format.parse('(41.02 ) ', '(#0.0###* )* '),
41.02)
self.assertEqual(self.format.parse('(4.102E1 ) ', '(0.0##E0##* )* '),
41.02)
def testParseDecimalWithGermanDecimalSeparator(self):
format = NumberFormat(symbols={'decimal': ',', 'group': '.'})
self.assertEqual(format.parse('1.234,567', '#,##0.000'), 1234.567)
def testParseWithAlternativeExponentialSymbol(self):
format = NumberFormat(
symbols={'decimal': '.', 'group': ',', 'exponential': 'X'})
self.assertEqual(format.parse('1.2X11', '#.#E0'), 1.2e11)
def testParseFailWithInvalidCharacters(self):
with self.assertRaises(NumberParseError):
self.format.parse('123xx', '###0.0#')
with self.assertRaises(NumberParseError):
self.format.parse('xx123', '###0.0#')
with self.assertRaises(NumberParseError):
self.format.parse('1xx23', '###0.0#')
Cheers! - Norbert
1 Like
mtrebron
(Norbert )
October 10, 2018, 11:26am
2
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)
kcleong
(Kim Chee Leong)
October 11, 2018, 8:44am
3
You could also use Babel , which is a Python library that assists in localizing numbers, dates and currencies. Regarding localisation of numbers: http://babel.pocoo.org/en/latest/numbers.html