-1

I was trying to convert strings like:

s = '1m'
s = '1.4m'
s = '1k'
s = '1.4k'

To what their actual integer is (e.g '1k' to 1000),

And I want a function that I can call with:

print(tonum('1m'))
print(tonum('1.4m'))
print(tonum('1.45m'))
print(tonum('1k'))
print(tonum('1.4k'))
print(tonum('1.45k'))

Output:

1000000
1400000
1450000
1000
1400
1450

I tried:

def tonum(s):
    if '.' in s:
        return int(s.replace('.', '').replace('m', '00000').replace('k', '00'))
    else:
        return int(s.replace('m', '000000').replace('k', '000'))

But it works only for 1.4k 1k 1.4m 1m, but not 1.45m.

U13-Forward
  • 69,221
  • 14
  • 89
  • 114

2 Answers2

3

You can maintain a dictionary and use that to lookup the right power of 10 to multiply by.

def convert_numeric_abbr(s):
    mapping = {'k': 1000, 'm': 1000000, 'b': 1000000000}
    # Do a check first so it doesn't choke on valid floats     
    if s[-1].isalpha():
        return float(s[:-1]) * mapping[s[-1].lower()]

    return float(s)

convert_numeric_abbr('1m')
# 1000000.0

convert_numeric_abbr('1.4m')
# 1400000.0

convert_numeric_abbr('1k')
# 1000.0

convert_numeric_abbr('1.4k')
# 1400.0
cs95
  • 379,657
  • 97
  • 704
  • 746
  • 1
    Very nice, just a note that In Python3 we could write also: `'b': 1_000_000_000` (PEP515) – VPfB Jun 11 '19 at 06:07
1

Although eval is evil, you can use this as a proof of concept:

def tonum(s):
    return eval(s.replace('k', '*1e3').replace('m', '*1e6'))

As a bonus, this will also correctly compute expressions such as:

tonum("140k + 1m")
Selcuk
  • 57,004
  • 12
  • 102
  • 110