Skip to content

Commit eef1d4e

Browse files
committed
User-level locale module. A wrapper around _locale which adds
format(), str(), atof(), and atoi(). The last three are locale sensitive versions of the corresponding standard functions (only for numbers though); format() does general %[efg] formatting taking the locale into account, optionally with thousands grouping.
1 parent 3df69bc commit eef1d4e

File tree

1 file changed

+75
-0
lines changed

1 file changed

+75
-0
lines changed

Lib/locale.py

Lines changed: 75 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,75 @@
1+
"Support for number formatting using the current locale settings"
2+
3+
from _locale import *
4+
import string
5+
6+
#perform the grouping from right to left
7+
def _group(s):
8+
conv=localeconv()
9+
grouping=conv['grouping']
10+
if not grouping:return s
11+
result=""
12+
while s and grouping:
13+
# if grouping is -1, we are done
14+
if grouping[0]==CHAR_MAX:
15+
break
16+
# 0: re-use last group ad infinitum
17+
elif grouping[0]!=0:
18+
#process last group
19+
group=grouping[0]
20+
grouping=grouping[1:]
21+
if result:
22+
result=s[-group:]+conv['thousands_sep']+result
23+
else:
24+
result=s[-group:]
25+
s=s[:-group]
26+
if s and result:
27+
result=s+conv['thousands_sep']+result
28+
return result
29+
30+
def format(f,val,grouping=0):
31+
"""Formats a value in the same way that the % formatting would use,
32+
but takes the current locale into account.
33+
Grouping is applied if the third parameter is true."""
34+
result = f % val
35+
fields = string.splitfields(result,".")
36+
if grouping:
37+
fields[0]=_group(fields[0])
38+
if len(fields)==2:
39+
return fields[0]+localeconv()['decimal_point']+fields[1]
40+
elif len(fields)==1:
41+
return fields[0]
42+
else:
43+
raise Error,"Too many decimal points in result string"
44+
45+
def str(val):
46+
"""Convert float to integer, taking the locale into account."""
47+
return format("%.12g",val)
48+
49+
def atof(str,func=string.atof):
50+
"Parses a string as a float according to the locale settings."
51+
#First, get rid of the grouping
52+
s=string.splitfields(str,localeconv()['thousands_sep'])
53+
str=string.join(s,"")
54+
#next, replace the decimal point with a dot
55+
s=string.splitfields(str,localeconv()['decimal_point'])
56+
str=string.join(s,'.')
57+
#finally, parse the string
58+
return func(str)
59+
60+
def atoi(str):
61+
"Converts a string to an integer according to the locale settings."
62+
return atof(str,string.atoi)
63+
64+
def test():
65+
setlocale(LC_ALL,"")
66+
#do grouping
67+
s1=format("%d",123456789,1)
68+
print s1,"is",atoi(s1)
69+
#standard formatting
70+
s1=str(3.14)
71+
print s1,"is",atof(s1)
72+
73+
74+
if __name__=='__main__':
75+
test()

0 commit comments

Comments
 (0)