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