On Thu, Oct 7, 2010 at 11:51 AM, C or L Smith <smi...@worksmail.net> wrote:
> 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? > s = ('%%%ig' % sigfigs) % n # double-% cancels the % ... 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 > -- > http://mail.python.org/mailman/listinfo/python-list > -- Jason M. Swails Quantum Theory Project, University of Florida Ph.D. Graduate Student 352-392-4032
-- http://mail.python.org/mailman/listinfo/python-list