New issue 272: D string format l10n
https://bitbucket.org/blais/beancount/issues/272/d-string-format-l10n

Michael Droogleever:

Localisation of the D() Decimal str parser. Currently it only accepts numbers 
with a '.' as the decimal separator and ',' as the thousands separator. e.g. 
"1,123.45"

This has been mentioned frequently before, in the context of wider i18n issues, 
but I could not find a specific issue for D. I am happy to create fix if simple 
enough. More thousands separators could be added to the regex, but that is not 
very sustainable.
Proposed fix, passes all existing beancount/core unittests:
```diff

--- a/beancount/core/number.py  Thu Apr 05 01:01:06 2018 -0400
+++ b/beancount/core/number.py  Fri Apr 06 00:07:17 2018 +0200
@@ -15,7 +15,10 @@
 import types
 import warnings
 import re
+import locale
 
+# TODO determine if locale can be pulled from options
+# TODO determine if locale needs to be restoed to 'C' portable locale after
+locale.setlocale(locale.LC_ALL, '')
 
 # Note: Python 3.3 is supposed to guarantee a fast "C" decimal implementation,
 # as it comes with its source code. However, in practice, many distributions,
@@ -67,10 +71,10 @@
 # errors that would occur from attempts to access incomplete data.
 class MISSING: pass
 
 # Regular expression for parsing a number in Python.
 NUMBER_RE = r"[+-]?\s*[0-9,]*(?:\.[0-9]*)?"
 
-_CLEAN_NUMBER_RE = re.compile('[, ]')
+_CLEAN_NUMBER_RE = re.compile("[,']")
 
 # pylint: disable=invalid-name
 def D(strord=None):
@@ -91,6 +95,10 @@
         if strord is None or strord == '':
             return Decimal()
         elif isinstance(strord, str):
+            strord = strord.replace(' ', '')
+            # Try using user's locale first
+            if locale.getlocale() != (None, None):
+                return Decimal(locale.delocalize(strord))
             return Decimal(_CLEAN_NUMBER_RE.sub('', strord))
         elif isinstance(strord, Decimal):
             return strord
```


-- 
You received this message because you are subscribed to the Google Groups 
"Beancount" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to beancount+unsubscr...@googlegroups.com.
To post to this group, send email to beancount@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/beancount/20180405222514.2706.57428%40celery-worker-110.ash1.bb-inf.net.
For more options, visit https://groups.google.com/d/optout.

Reply via email to