Python任意数字到非科学字符串 [英] Python any number to non-scientific string

查看:61
本文介绍了Python任意数字到非科学字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在 python 中有一个函数,它可以处理从非常大到非常小的数字,甚至是带有小数点右边一小部分的大数字(见下面的代码).我需要将数字转换为字符串并删除它可能具有的任何科学记数法.我还需要删除小数点右侧的尾随零.这是我迄今为止最接近的解决方案,它适用于大多数数字,但并非如您所见.

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)   

结果:

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

推荐答案

from decimal import Decimal

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

这篇关于Python任意数字到非科学字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆