Python any number to non-scientific string

喜你入骨 提交于 2019-12-11 06:23:51

问题


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

回答1:


from decimal import Decimal

def number2string(a):
    b = format(Decimal(str(a)).normalize(), 'f')
    print a,"->",b


来源:https://stackoverflow.com/questions/22696919/python-any-number-to-non-scientific-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!