Added 'list_only' option (and modified 'run()' to respect it).
[python/dscho.git] / Lib / fpformat.py
blob74f5698d1bf5750556ac36b2e1fab398ee1f5d97
1 # General floating point formatting functions.
3 # Functions:
4 # fix(x, digits_behind)
5 # sci(x, digits_behind)
7 # Each takes a number or a string and a number of digits as arguments.
9 # Parameters:
10 # x: number to be formatted; or a string resembling a number
11 # digits_behind: number of digits behind the decimal point
14 import re
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')
24 try:
25 class NotANumber(ValueError):
26 pass
27 except TypeError:
28 NotANumber = 'fpformat.NotANumber'
30 # Return (sign, intpart, fraction, expo) or raise an exception:
31 # sign is '+' or '-'
32 # intpart is 0 or more digits beginning with a nonzero
33 # fraction is 0 or more digits
34 # expo is an integer
35 def extract(s):
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
45 # Remove the exponent by changing intpart and fraction
46 def unexpo(intpart, fraction, expo):
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
59 # Round or extend the fraction to size digs
60 def roundfrac(intpart, fraction, 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, ''
85 # Format x as [-]ddd.ddd with 'digs' digits after the point
86 # and at least one digit before.
87 # If digs <= 0, the point is suppressed.
88 def fix(x, digs):
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
101 # Format x as [-]d.dddE[+-]ddd with 'digs' digits after the point
102 # and exactly one digit before.
103 # If digs is <= 0, one digit is kept and the point is suppressed.
104 def sci(x, digs):
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
133 # Interactive test run
134 def test():
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