Skip to content

Instantly share code, notes, and snippets.

@gajeshbhat
Last active October 31, 2023 19:41
Show Gist options
  • Save gajeshbhat/67a3db79a6aecd1db42343190f9a2f17 to your computer and use it in GitHub Desktop.
Save gajeshbhat/67a3db79a6aecd1db42343190f9a2f17 to your computer and use it in GitHub Desktop.
Convert k to Integer thousand Python.
def convert_str_to_number(x):
total_stars = 0
num_map = {'K':1000, 'M':1000000, 'B':1000000000}
if x.isdigit():
total_stars = int(x)
else:
if len(x) > 1:
total_stars = float(x[:-1]) * num_map.get(x[-1].upper(), 1)
return int(total_stars)
@asadamatic
Copy link

Add the following line,

elif ',' in x:

    total_stars = float(x.replace(',','')) # removing ,

@SanthoshBala18
Copy link

def convert_str_to_number(x):
    total_stars = 0
    num_map = {'K':1000, 'M':1000000, 'B':1000000000}
    if x.isdigit():
        total_stars = int(x)
    else:
        if len(x) > 1:
            total_stars = float(x[:-1]) * num_map.get(x[-1].upper(), 1)
    return int(total_stars)

@gajeshbhat
Copy link
Author

def convert_str_to_number(x):
    total_stars = 0
    num_map = {'K':1000, 'M':1000000, 'B':1000000000}
    if x.isdigit():
        total_stars = int(x)
    else:
        if len(x) > 1:
            total_stars = float(x[:-1]) * num_map.get(x[-1].upper(), 1)
    return int(total_stars)

This looks more clean. Updated this. Thank you.

@S14-dot
Copy link

S14-dot commented May 14, 2021

how can i convert thousand into million

@s3rgeym
Copy link

s3rgeym commented Oct 31, 2023

>>> def str_to_number(s: str) -> int:
...     import re
...     units = ["k", "m", "g"]
...     rv, unit, *_ = re.findall(r'\d+|[a-z]', s, re.I) + [""]
...     return int(rv) * (1 << abs(~units.index(unit.lower())) * 10 if unit else 1)
... 
>>> str_to_number(' 128')
128
>>> str_to_number(' 128M ')
134217728
>>> str_to_number(' 128 Mebybites ')
134217728

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment