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 = ['?', '?', '?']
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 = ['?', '?', '?']
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**2, 'GB':1024**3, '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='MB'
>>> ['{:0.2} {}'.format(e/defs[sd], sd) for e in bytes]
['1e+03 MB', '2.5e+03 MB', '0.39 MB']
>>> sd='TB'
>>> ['{:0.2} {}'.format(e/defs[sd], sd) for e in bytes]
['0.00095 TB', '0.0024 TB', '3.7e-07 TB']
Heres something I found online.
def conv_KB_to_MB(input_kilobyte):
megabyte = 1./1000
convert_mb = megabyte * input_kilobyte
return convert_mb
def conv_MB_to_GB(input_megabyte):
gigabyte = 1.0/1024
convert_gb = gigabyte * input_megabyte
return convert_gb
#Create the menu
print "Enter 1 to convert from KBs to MBs"
print "Enter 2 to convert from MBs to GBs"
try:
menu_choice = (raw_input("Enter a selection"))
except ValueError:
print "This is not a number"
except NameError:
print "Name Error"
except SystenError:
print "Syntax Error"
if menu_choice == '1':
kb_input = float(input("Enter KBs"))
megabytes = conv_KB_to_MB(kb_input)
print megabytes
elif menu_choice == '2':
mb_input = float(input("Enter MBs"))
gigabytes = conv_MB_to_GB(mb_input)
print gigabytes
else:
print "exiting"