[Tutor] Python 3.1: How to print a very large number to n significant digits?

Richard D. Moores rdmoores at gmail.com
Mon Nov 23 21:56:42 CET 2009


On Mon, Nov 23, 2009 at 12:23, Wayne Werner <waynejwerner at gmail.com> wrote:
> On Mon, Nov 23, 2009 at 12:28 PM, Richard D. Moores <rdmoores at gmail.com>
> wrote:
>>
>> Can't find the answer in the docs for 3.1
>>
>> To print 123**34.6 to 5 sig digits,
>>
>> print("%.*e" % (4, 123**34.6))
>>
>> will do the job:
>>
>> >>> print("%.*e" % (4, 123**34.6))
>> 2.0451e+72
>>
>> However, if the number is 123**346, using
>>
>> print("%.*e" % (4, 123**346))
>>
>> gets me
>>
>> >>> print("%.*e" % (5, 123**346))
>> Traceback (most recent call last):
>>  File "<pyshell#28>", line 1, in <module>
>>    print("%.*e" % (5, 123**346))
>> OverflowError: Python int too large to convert to C double
>
> Try the decimal module:
> http://docs.python.org/library/decimal.html
> HTH,
> Wayne

Yes, I just found this function in my collection of functions. I
believe I wrote this one myself, but I can't remember for sure:

=======================================
def numberRounding(n, significantDigits):
    """
    Rounds a string in the form of a string number
    (float or integer, negative or positive) to any number of
    significant digits. If an integer, there is no limitation on it's size.
    Safer to always have n be a string.
    """
    import decimal
    def d(x):
        return decimal.Decimal(str(x))
    decimal.getcontext().prec = significantDigits
    s = str(d(n)/1)
    s = s.lstrip('0')
    return s
=======================================

>>> numberRounding(123**346,5)
'1.2799E+723'
>>> numberRounding(123**34.6,5)
'2.0451E+72'
>>> numberRounding(12345**6789,3)
'1.36E+27777'
>>> numberRounding(3.4**-12.9,6)
'1.39291E-7'

Dick


More information about the Tutor mailing list