-4

I want to convert the numbers which come with the letters and convert it based on the value each letter specifies. Like a number 1M should be read as 1000000 and a number 1K should be read as 1000. Is there some simple method to get this done?

Rakesh Nittur
  • 445
  • 1
  • 7
  • 20
  • 6
    You could try writing some code to solve your problem :) – blacksite Jan 09 '17 at 15:46
  • I saw the [pint](https://pint.readthedocs.io/en/0.7.2/) library referenced in another answer a few days ago. I haven't used it myself but it may be suitable for you. Correct me if I'm wrong. – Tagc Jan 09 '17 at 15:49
  • Possible duplicate of [Python library to convert between SI unit prefixes](http://stackoverflow.com/questions/10969759/python-library-to-convert-between-si-unit-prefixes) – ThisSuitIsBlackNot Jan 09 '17 at 15:57

3 Answers3

1

Convert the last character to a value, e.g. M -> 1000000, k -> 1000. Multipy with the value and add some code for possible parse errors.

(I deliberately did not add code here to let you give it a try).

Michel Keijzers
  • 15,025
  • 28
  • 93
  • 119
1

A trivial approach would be to use a dictionary to store the number of zeros each conversion would use:

>>> number = {
...     'K': 3,
...     'M': 6
... }
>>> 
>>> var = '5M'
>>> int(var[0] + ('0' * number[var[1]]))
5000000
>>> var = '2K'
>>> int(var[0] + ('0' * number[var[1]]))
2000
>>> 

This solution may or may not be scalable depending on the size and complexity of your project.

Christian Dean
  • 22,138
  • 7
  • 54
  • 87
0

You can use Prefixed to convert to a float. prefixed.Float is a subclass of the builtin float and is the same except it allows formatting with SI and IEC prefixes.

>>> from prefixed import Float
>>> Float('1M')
Float(1000000.0)

If you want an integer

>>> int(Float('1M'))
1000000

If you want to convert back, just add 'h' as a format specifier and use '.#' to set precision.

>>> value = Float('1M')
>>> f'{value:.0h}'
'1M'
>>> f'{value:.2h}'
'1.00M'

In the case of 1K, that's not SI notation, the prefix for kilo is k, so you'd need to make it lowercase. Just be careful with those because M is Mega and m is Milli. Pretty big difference there! Supported prefixes are listed here.

>>> Float('1K'.lower())
Float(1000.0)

If K is for kibi, you need to add an 'i' so it Prefixed knows you want IEC prefixes,

>>> Float('1Ki')
Float(1024.0)
aviso
  • 2,371
  • 1
  • 14
  • 15