home *** CD-ROM | disk | FTP | other *** search
/ PC World 2001 April / PCWorld_2001-04_cd.bin / Software / TemaCD / webclean / !!!python!!! / BeOpen-Python-2.0.exe / FPFORMAT.PY < prev    next >
Encoding:
Python Source  |  2000-09-28  |  4.6 KB  |  142 lines

  1. """General floating point formatting functions.
  2.  
  3. Functions:
  4. fix(x, digits_behind)
  5. sci(x, digits_behind)
  6.  
  7. Each takes a number or a string and a number of digits as arguments.
  8.  
  9. Parameters:
  10. x:             number to be formatted; or a string resembling a number
  11. digits_behind: number of digits behind the decimal point
  12. """
  13.  
  14. import re
  15.  
  16. # Compiled regular expression to "decode" a number
  17. decoder = re.compile(r'^([-+]?)0*(\d*)((?:\.\d*)?)(([eE][-+]?\d+)?)$')
  18. # \0 the whole thing
  19. # \1 leading sign or empty
  20. # \2 digits left of decimal point
  21. # \3 fraction (empty or begins with point)
  22. # \4 exponent part (empty or begins with 'e' or 'E')
  23.  
  24. try:
  25.     class NotANumber(ValueError):
  26.         pass
  27. except TypeError:
  28.     NotANumber = 'fpformat.NotANumber'
  29.  
  30. def extract(s):
  31.     """Return (sign, intpart, fraction, expo) or raise an exception:
  32.     sign is '+' or '-'
  33.     intpart is 0 or more digits beginning with a nonzero
  34.     fraction is 0 or more digits
  35.     expo is an integer"""
  36.     res = decoder.match(s)
  37.     if res is None: raise NotANumber, s
  38.     sign, intpart, fraction, exppart = res.group(1,2,3,4)
  39.     if sign == '+': sign = ''
  40.     if fraction: fraction = fraction[1:]
  41.     if exppart: expo = int(exppart[1:])
  42.     else: expo = 0
  43.     return sign, intpart, fraction, expo
  44.  
  45. def unexpo(intpart, fraction, expo):
  46.     """Remove the exponent by changing intpart and fraction."""
  47.     if expo > 0: # Move the point left
  48.         f = len(fraction)
  49.         intpart, fraction = intpart + fraction[:expo], fraction[expo:]
  50.         if expo > f:
  51.             intpart = intpart + '0'*(expo-f)
  52.     elif expo < 0: # Move the point right
  53.         i = len(intpart)
  54.         intpart, fraction = intpart[:expo], intpart[expo:] + fraction
  55.         if expo < -i:
  56.             fraction = '0'*(-expo-i) + fraction
  57.     return intpart, fraction
  58.  
  59. def roundfrac(intpart, fraction, digs):
  60.     """Round or extend the fraction to size digs."""
  61.     f = len(fraction)
  62.     if f <= digs:
  63.         return intpart, fraction + '0'*(digs-f)
  64.     i = len(intpart)
  65.     if i+digs < 0:
  66.         return '0'*-digs, ''
  67.     total = intpart + fraction
  68.     nextdigit = total[i+digs]
  69.     if nextdigit >= '5': # Hard case: increment last digit, may have carry!
  70.         n = i + digs - 1
  71.         while n >= 0:
  72.             if total[n] != '9': break
  73.             n = n-1
  74.         else:
  75.             total = '0' + total
  76.             i = i+1
  77.             n = 0
  78.         total = total[:n] + chr(ord(total[n]) + 1) + '0'*(len(total)-n-1)
  79.         intpart, fraction = total[:i], total[i:]
  80.     if digs >= 0:
  81.         return intpart, fraction[:digs]
  82.     else:
  83.         return intpart[:digs] + '0'*-digs, ''
  84.  
  85. def fix(x, digs):
  86.     """Format x as [-]ddd.ddd with 'digs' digits after the point
  87.     and at least one digit before.
  88.     If digs <= 0, the point is suppressed."""
  89.     if type(x) != type(''): x = `x`
  90.     try:
  91.         sign, intpart, fraction, expo = extract(x)
  92.     except NotANumber:
  93.         return x
  94.     intpart, fraction = unexpo(intpart, fraction, expo)
  95.     intpart, fraction = roundfrac(intpart, fraction, digs)
  96.     while intpart and intpart[0] == '0': intpart = intpart[1:]
  97.     if intpart == '': intpart = '0'
  98.     if digs > 0: return sign + intpart + '.' + fraction
  99.     else: return sign + intpart
  100.  
  101. def sci(x, digs):
  102.     """Format x as [-]d.dddE[+-]ddd with 'digs' digits after the point
  103.     and exactly one digit before.
  104.     If digs is <= 0, one digit is kept and the point is suppressed."""
  105.     if type(x) != type(''): x = `x`
  106.     sign, intpart, fraction, expo = extract(x)
  107.     if not intpart:
  108.         while fraction and fraction[0] == '0':
  109.             fraction = fraction[1:]
  110.             expo = expo - 1
  111.         if fraction:
  112.             intpart, fraction = fraction[0], fraction[1:]
  113.             expo = expo - 1
  114.         else:
  115.             intpart = '0'
  116.     else:
  117.         expo = expo + len(intpart) - 1
  118.         intpart, fraction = intpart[0], intpart[1:] + fraction
  119.     digs = max(0, digs)
  120.     intpart, fraction = roundfrac(intpart, fraction, digs)
  121.     if len(intpart) > 1:
  122.         intpart, fraction, expo = \
  123.             intpart[0], intpart[1:] + fraction[:-1], \
  124.             expo + len(intpart) - 1
  125.     s = sign + intpart
  126.     if digs > 0: s = s + '.' + fraction
  127.     e = `abs(expo)`
  128.     e = '0'*(3-len(e)) + e
  129.     if expo < 0: e = '-' + e
  130.     else: e = '+' + e
  131.     return s + 'e' + e
  132.  
  133. def test():
  134.     """Interactive test run."""
  135.     try:
  136.         while 1:
  137.             x, digs = input('Enter (x, digs): ')
  138.             print x, fix(x, digs), sci(x, digs)
  139.     except (EOFError, KeyboardInterrupt):
  140.         pass
  141.  
  142.