Search code examples
pythonpython-3.xregexnumberspython-3.7

How to change 0.9M to float number Python3?


Is there a Python3 library that convert abrriviation of string number as : 10K, 0.2M, 32B etc. to float numbers?

exmple: 10K => 10000 0.9M=> 9000000 an so on.

If there isn't a library what is the efficient way to convernt those numbers?

**I tried to split the number from the letter but it only works with int and not double.

test_str = "9M"
temp = re.compile("([0-9]+)([a-zA-Z]+)")
res = temp.match(test_str).groups()

More info: I get the number from the client that way and can't change it. It needed to be float for late calculations

Thanks !


Solution

  • Try

    >>> import re
    >>>
    >>> fact_dic = {'': 1, 'K': 1000, 'M': 1000000}
    >>>
    >>> def GetFloatFromFactor( input ):
    ...     m = re.search( r"^(\d+(?:\.\d*)?|\.\d+)([KM]?)$", input)
    ...     if m != None:
    ...         fval = float( m.group(1) ) * fact_dic[ m.group(2) ]
    ...         return fval
    ...     else:
    ...         return "no match"
    ...
    >>> GetFloatFromFactor( '3K' )
    3000.0
    >>> GetFloatFromFactor( '12.4M' )
    12400000.0
    >>> GetFloatFromFactor( '098.281' )
    98.281