Question

I would like to have a function in python that can handle a diverse range of numbers from very large to very small and even large numbers with a small fraction right of the decimal (see code below). I need to convert the number to a string and remove any scientific notation it may have. I also need to remove trailing zeros right of the decimal point. This is the closest solution I have so far and it works for most numbers, but not all as you can see.

Are there any improvements that can be made to support troublesome numbers?

def number2string(a):
    b = '{0:.15f}'.format(a)
    b = b.rstrip('0')   # remove trailing zeros right of decimal
    b = b.rstrip('.')   # remove trailing decimal if exists
    print a,"->",b

number2string(3)
number2string(3.14)
number2string(3.14E+12)
number2string(3.14e-7)
number2string(1234567.007)
number2string(12345678901234567890)
number2string(.00000000000000123)   

Results:

3 -> 3
3.14 -> 3.14
3.14e+12 -> 3140000000000
3.14e-07 -> 0.000000314
1234567.007 -> 1234567.006999999983236
12345678901234567890 -> 12345678901234567168
1.23e-15 -> 0.000000000000001
Was it helpful?

Solution

from decimal import Decimal

def number2string(a):
    b = format(Decimal(str(a)).normalize(), 'f')
    print a,"->",b
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top