Search code examples
pythonregexnumbersmetric

Convert string with engineer prefix to float


I have a string like '102.3k' I would like to convert this string with an engineer prefix notation to a float number.

http://en.wikipedia.org/wiki/Engineering_notation

Allowed prefixes are

posPrefixes = ['k', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y']
negPrefixes = ['m', 'µ', 'n', 'p', 'f', 'a', 'z', 'y']

k means 10^3

M means 10^6

m means 10^-3

µ means 10^-6

I think I should use regex to do this but I have very few experience with regex.

edit: ideally the solution should also be able to convert any string so '102.3' (without prefix) should also be converted to float


Solution

  • Try this out, no regex needed:

    pos_postfixes = ['k', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y']
    neg_postfixes = ['m', 'µ', 'n', 'p', 'f', 'a', 'z', 'y']
    
    num_postfix = n[-1]
    if num_postfix in pos_postfixes:
        num = float(n[:-1])
        num*=10**((pos_postfixes.index(num_postfix)+1)*3)
    elif num_postfix in neg_postfixes:
        num = float(n[:-1])
        num*=10**(-(neg_postfixes.index(num_postfix)+1)*3)
    else:
        num = float(n)
    print(num)
    

    Another thing to note is that in python, it is more common to use underscore variable names than camelcasing, see the pep-8: http://www.python.org/dev/peps/pep-0008/