[Tutor] Rounding a float to n significant digits

Dick Moores rdm at rcblue.com
Mon Dec 4 11:33:15 CET 2006


At 12:52 PM 11/30/2006, Dick Moores wrote:
>At 11:19 PM 11/27/2006, Dick Moores wrote:
> >I just dug this Tim Smith creation out of the Tutor archive.
> >
> >def round_to_n(x, n):
> >         """
> >         Rounds float x to n significant digits, in scientific notation.
> >         Written by Tim Peters. See his Tutor list post of 7/3/04 at
> >         http://mail.python.org/pipermail/tutor/2004-July/030324.html
> >         """
> >         if n < 1:
> >                 raise ValueError("number of significant digits 
> must be >= 1")
> >         return "%.*e" % (n-1, x)
> >
> >Thought others might find it of use.
> >
> >Dick Moores
>
>I've run into the limitation on the size of an int that can be
>converted to a float.

I back with this topic.

I'd completely forgotten that I had written numberRounding(), which 
doesn't suffer from that limitation:

def numberRounding(n, significantDigits=4):
         import decimal
         def d(x):
                 return decimal.Decimal(str(x))
         decimal.getcontext().prec = significantDigits
         return d(n)/d(1)

Thus,
 >>> n = 2**2000
 >>> print numberRounding(n,6)
1.14813E+602

BTW the last line of numberRounding() seems strange (even though it 
works)? Why wouldn't "return d(n)" do the job?

Thanks,

Dick Moores




More information about the Tutor mailing list