在使用通用格式将浮点转换为字符串时,如何抑制科学记数法?

2024-05-13 09:22:39 发布

您现在位置:Python中文网/ 问答频道 /正文

考虑以下浮动列表:

A = [3.7432, 0.37432, 0.037432, 0.0037432, 0.00037432, 3.4327e-05, \
     3.7432e-06, 3.7432e-07, 3.7432e-08, 3.7432e-09, 3.7432e-10]

我想将这些字符串转换为(1)四舍五入到第一个有效数字的字符串列表,以及(2)不使用科学符号的字符串列表

为此,我使用以下代码:

[f"{a:.1g}" for a in A]

这就是我得到的:

['4', '0.4', '0.04', '0.004', '0.0004', '4e-05', '4e-06', '4e-07', '4e-08', '4e-09', '4e-10',]

但是,我希望的输出是:

['4', '0.4', '0.04', '0.004', '0.0004', '0.00004', '0.000004', '0.0000004', '0.00000004', '0.000000004']

我的问题是,实现这一目标的简单方法是什么

如果这是一个重复的道歉。我曾经问过很多类似的问题,但没有一个专门针对我的问题

编辑:在@nagyl的帮助下,我制作了一个函数,可以实现我想要的功能:

def float_to_fsf(x):
    """
    Converts float to string with one significant figure
    while refraining from scientific notation

    inputs:
        x: input float to be converted to string (float)
    """

    import numpy as np

    # Get decimal exponent of input float
    exp = int(f"{x:e}".split("e")[1])

    # Get rid of all digits after the first significant figure
    x_fsf = round(x*10**-exp, 0) * 10**exp

    # Get rid of scientific notation and convert to string
    x_str = np.format_float_positional(x_fsf)

    # Return string output
    return x_str

Tags: ofto字符串列表inputgetstringnp
1条回答
网友
1楼 · 发布于 2024-05-13 09:22:39

您可以从numpy使用format_float_positional

for i in range(len(a)):
    a[i] = str(numpy.format_float_positional(a[i]))

或具有列表理解能力:

a = [str(numpy.format_float_positional(elem)) for elem in a]

相关问题 更多 >