blob: d85cabfca5898287a0f27a5eaa9b3d55516b93c1 [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:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +000014 # 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]
Guido van Rossumeef1d4e1997-11-19 19:01:43 +000027 if s and result:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +000028 result=s+conv['thousands_sep']+result
Guido van Rossumeef1d4e1997-11-19 19:01:43 +000029 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:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +000038 fields[0]=_group(fields[0])
Guido van Rossumeef1d4e1997-11-19 19:01:43 +000039 if len(fields)==2:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +000040 return fields[0]+localeconv()['decimal_point']+fields[1]
Guido van Rossumeef1d4e1997-11-19 19:01:43 +000041 elif len(fields)==1:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +000042 return fields[0]
Guido van Rossumeef1d4e1997-11-19 19:01:43 +000043 else:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +000044 raise Error,"Too many decimal points in result string"
Guido van Rossumeef1d4e1997-11-19 19:01:43 +000045
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()