2

I have variables with values like 1.7m 1.8k and 1.2b how can I convert them to a real number value for example

1.7m = 1700000
1.8k = 1800
1.2b = 1200000000
Pevo
  • 55
  • 2
  • 6

4 Answers4

11

I would define a dictionary:

tens = dict(k=10e3, m=10e6, b=10e9)

then

x='1.7m'
factor, exp = x[0:-1], x[-1].lower()
ans = int(float(factor) * tens[exp])
S.Lott
  • 384,516
  • 81
  • 508
  • 779
Vicki Laidler
  • 3,415
  • 1
  • 20
  • 17
1

You might be interested in a units library like quantities or unum.

Mike Graham
  • 73,987
  • 14
  • 101
  • 130
1

Using lambda:

>>> tens = {'k': 10e3, 'm': 10e6, 'b': 10e9}
>>> f = lambda x: int(float(x[:-1])*tens[x[-1]])
>>> f('1.7m')
17000000
>>> f('1.8k')
18000
>>> f('1.2b')
12000000000
riza
  • 16,274
  • 7
  • 29
  • 29
0

Here is an example using re:

input = '17k, 14.05m, 1.235b'

multipliers = { 'k': 1e3,
                'm': 1e6,
                'b': 1e9,
              }

pattern = r'([0-9.]+)([bkm])'

for number, suffix in re.findall(pattern, input):
    number = float(number)
    print number * multipliers[suffix]
Joe Koberg
  • 25,416
  • 6
  • 48
  • 54
  • 1
    Or even `pattern = r'([0-9.]+)(%s)' % '|'.join(multipliers)` to avoid the minor repetition of units in there. – Will McCutchen Mar 15 '10 at 20:05
  • @Will, being that `[bkm]` will only match one character, I don't see how there could be a "minor repetition of units in there". I do like your suggestion of doing a join on multipliers, but not for the reason you stated. – tgray Mar 15 '10 at 21:25
  • 1
    He is saying you can use the already-specified dictionary keys to fill out the RE rather than retyping 'bkm'. – Joe Koberg Mar 15 '10 at 21:29
  • But i considered that less easy to understand in this simple case. If the dict had all the SI prefixes in it or somesuch, I would definitely have done that. – Joe Koberg Mar 15 '10 at 21:30
  • Using regex here is quite unnecessary. – Mike Graham Mar 15 '10 at 23:08
  • Mike: Please feel free to provide a simpler or more effective answer. – Joe Koberg Mar 15 '10 at 23:39
  • @Joe, Vicki Laidler's answer uses the same technique as yours except that it grabs the last character directly rather than based on matching a regular expression. I suspect most people would find that solution more readable; I know I did. – Mike Graham Mar 16 '10 at 02:42
  • @Mike: There are more than one way to solve a problem, and I've learned that it's good to adopt the unix philosophy of being forgiving in your input and precise in output.... This example shows that the regex can pull out the formatted numbers even with noise characters such as ' ' and ',', and even extracts many such numbers from the input with very little additional work. The other solution solves the problem but is more "brittle". – Joe Koberg Mar 16 '10 at 15:34