home *** CD-ROM | disk | FTP | other *** search
/ OS/2 Shareware BBS: 10 Tools / 10-Tools.zip / pytho152.zip / emx / lib / python1.5 / locale.py < prev    next >
Text File  |  2000-08-10  |  2KB  |  77 lines

  1. "Support for number formatting using the current locale settings"
  2. # Author: Martin von Loewis
  3.  
  4. from _locale import *
  5. import string
  6.  
  7. #perform the grouping from right to left
  8. def _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.  
  31. def 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.     
  46. def str(val):
  47.     """Convert float to integer, taking the locale into account."""
  48.     return format("%.12g",val)
  49.  
  50. def 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.  
  61. def atoi(str):
  62.     "Converts a string to an integer according to the locale settings."
  63.     return atof(str,string.atoi)
  64.  
  65. def 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.  
  75. if __name__=='__main__':
  76.     test()
  77.