'How to convert SI units to number using python
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?
Solution 1:[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).
Solution 2:[2]
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.
Solution 3:[3]
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)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Michel Keijzers |
| Solution 2 | Christian Dean |
| Solution 3 | aviso |
