简体   繁体   中英

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?

Convert the last character to a value, eg 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).

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM