Haliaetus
Haliaetus

Reputation: 490

How to suppress scientific notation when converting a float to string using general format?

Consider the following list of floats:

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]

I would like to convert these to a list of strings that are (1) rounded to the first significant figure, and (2) are not in scientific notation.

I'm using the following code for this purpose:

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

And this is what I'm getting:

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

However, my desired output would be this:

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

My question is, what would be a simple way to achieve this?

Apologies if this is a duplicate. I've gone through a bunch of similar questions but none of them addressed my issue specifically.

EDIT: with the help of @nagyl, I made a function that does what I want:

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

Upvotes: 0

Views: 927

Answers (1)

nagyl
nagyl

Reputation: 1644

You can use format_float_positional from numpy.

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

Or with list comprehension:

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

Upvotes: 2

Related Questions