将负面科学记数法1.3E-2转换为浮动?

问题描述 投票:0回答:3

我知道我可以将科学记数法中的数字转换为float的浮点数,如下所示:

>>> x = 1.3e8
>>> float(x)
130000000.0

那么,为什么我不能用负指数做同样的事情呢?

>>> x = 1.3e-8
>>> x
1.3e-08
>>> float(x)
1.3e-08

在最后一个案例中,我本来期望float(x)0.000000013

python floating-point scientific-notation
3个回答
1
投票

1.3e-8是一个浮点文字(即它直接创建一个float对象),所以你不需要将它包装在float()中。 Python shell只返回float的默认字符串表示形式。要强制使用定点表示法,可以使用str.format(),尽管您可能需要指定精度:

>>> '{:.9f}'.format(1.3e-8)
'0.000000013'

0
投票

它已经是一个浮点数,它只是用科学记数法表示

print(type(1.3e8)) # <class 'float'>
print(type(1.3e-8)) # <class 'float'>
print(0.000000013)  # 1.3e-08

0
投票

以下函数处理任意数量的浮点。

def displayfloat(x):
    # format numbers > 1.
    if str(x).find('+') > -1:
        return '{:.1f}'.format(x)
    e_idx = str(x).find('e')
    # format numbers > 1e-05
    if e_idx == -1:
        return str(x)
    # format numbers < 1e-05
    minus_idx = str(x).find('-')
    shift = e_idx
    if str(x).find('.') > -1:
        shift -= 1
    decimalpoints = -int(str(x)[str(x).find('-'):]) - 1 + shift
    floatformat = '{:.'+str(decimalpoints)+'f}'
    return floatformat.format(x)
# exmaples
displayfloat(1e-5) # --> '0.00001'
displayfloat(1.1e-5) # --> '0.000011'
displayfloat(1e+5) # --> '100000.0'
© www.soinside.com 2019 - 2024. All rights reserved.