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