user1107049 user1107049 - 3 months ago 18
Python Question

How to convert MB to GB with precision in Python

What would be the fastest way to covert the values given in MB and KB to GB and TB?

sizes = ['999.992 MB', '2.488 GB', '401 KB']


sizes_in_GB = ['?', '?', '?']

sizes_in_TB = ['?', '?', '?']

Answer

Given:

>>> sizes = ['999.992 MB', '2.488 GB', '401 KB']

First agree on what 'precision' means. Since your input is a float, it is a fair assumption that 'precision' is limited to the input precision.

To calculate, first convert to base bytes (know though that your actual precision is no better than the input precision):

>>> defs={'KB':1024, 'MB':1024*1024, 'GB':1024*1024*1024, 'TB':1024**4} 
>>> bytes=[float(lh)*defs[rh] for lh, rh in [e.split() for e in sizes]]
>>> bytes
[1048567611.392, 2671469658.112, 410624.0]

Then convert to magnitude desired:

>>> sd='GB'
>>> ['{:0.2} {}'.format(e/defs[sd], sd) for e in bytes]
['0.98 GB', '2.5 GB', '0.00038 GB']
>>> sd='TB'
>>> ['{:0.2} {}'.format(e/defs[sd], sd) for e in bytes]
['1e+03 MB', '2.5e+03 MB', '0.39 MB']
>>> ['{:0.2} {}'.format(e/defs[sd], sd) for e in bytes]
['0.00095 TB', '0.0024 TB', '3.7e-07 TB']