jeudi 9 avril 2020

Python - Function to convert scientific notation to use prefixes (eg milli, micro)

I have created a fucntion that converts a number in scientific notation into one that uses prefxies eg where e-3 = m, e3 = k etc

Here is the code (I add extra 0s to those with a length less than 9 for formatting reasons):

def convertExpToSI(size):
if (abs(size) >= 1):
    if (abs(size) > 1e+31):
        return "{:.3e}".format(size)
    else:
        for x in [' ', 'K', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y', 'R', 'Q']:
            if abs(size) < 1000.0:
                y = "%3.3f %s" % (size, x)
                if (len(y) == 7):
                    y = '00' + y
                    return y
                elif (len(y) == 8):
                    y = '0' + y
                    return y
                else:
                    return y
            size /= 1000.0

if (abs(size) < 1):
    if (abs(size) < 1e-31):
        return "{:.3e}".format(size)
    else:
        for x in [' ', 'm', 'u', 'n', 'p', 'f', 'a', 'z', 'y', 'r', 'q']:
            if abs(size) > 0.001:
                y = "%3.3f %s" % (size, x)
                if (len(y) == 7):
                    y = '00' + y
                    return y
                elif (len(y) == 8):
                    y = '0' + y
                    return y
                else:
                    return y

            size /= 0.001

And this works but in some cases I feel it could be improved but my attempts have failed.

Currently with an input of print(convertExpToSI(2.855e-06)) the output is 000.003 m.

But also this could be written as 2.855 u which would be better as more data is retained.

What is confusing me more is that this works with numbers greater than 1. print(convertExpToSI(2.855e+06)) gives 002.855 M which is correct and shows more data.

Any help in this is greatly appreciated, Thank you!

Aucun commentaire:

Enregistrer un commentaire