mantissa and exponent in base 10

C or L Smith smiles at worksmail.net
Thu Oct 7 17:51:55 CEST 2010


I just sent a similar suggestion to tutor: check out the %g format.

>>> print '%g' % 1.2345e7
1.2345e+07
>>> print '%g' % 1.2345e-7
1.2345e-07
>>> print '%g' % 1.2345
1.2345

>>> def me(n, sigfigs = 4):
...  s = ('%.'+'%ig' % sigfigs) % n # check docs for a better way?
...  if 'e' in s: m, e = s.split('e')
...  else: m, e = s, 0
...  m, e = float(m), float(e)
...  if m >= 10:
...   m /= 100
...   e += 2
...  elif m >= 1:
...   m /= 10
...   e += 1
...  return m, e
... 
>>> me(9.9999999)
(0.10000000000000001, 2.0)
>>> me(12345)
(0.12350000000000001, 5.0)
>>> me(1.2345e-9)
(0.12350000000000001, -8.0)
>>> me(1.2345e-9, 2)
(0.12, -8.0)

Best regards,
 Chris Smith



More information about the Python-list mailing list