Significant figures calculation

Chris Torek nospam at torek.net
Sat Jun 25 15:04:52 EDT 2011


In article <mailman.386.1308949143.1164.python-list at python.org>
Jerry Hill  <malaclypse2 at gmail.com> wrote:
>I'm curious.  Is there a way to get the number of significant digits
>for a particular Decimal instance?

Yes:

def sigdig(x):
    "return the number of significant digits in x"
    return len(x.as_tuple()[1])

import decimal
D = decimal.Decimal

for x in (
    '1',
    '1.00',
    '1.23400e-8',
    '0.003'
):
    print 'sigdig(%s): %d' % (x, sigdig(D(x)))
-- 
In-Real-Life: Chris Torek, Wind River Systems
Intel require I note that my opinions are not those of WRS or Intel
Salt Lake City, UT, USA (40°39.22'N, 111°50.29'W)  +1 801 277 2603
email: gmail (figure it out)      http://web.torek.net/torek/index.html



More information about the Python-list mailing list