blob: 99354787b4235ae4b0d68ff7915e5ba48095b330 [file] [log] [blame]
Guido van Rossumeef1d4e1997-11-19 19:01:43 +00001"Support for number formatting using the current locale settings"
2
3from _locale import *
4import string
5
6#perform the grouping from right to left
7def _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
30def 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
45def str(val):
46 """Convert float to integer, taking the locale into account."""
47 return format("%.12g",val)
48
49def 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
60def atoi(str):
61 "Converts a string to an integer according to the locale settings."
62 return atof(str,string.atoi)
63
64def 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
74if __name__=='__main__':
75 test()