如何在Python中精确地将MB转换为GB

时间:2016-09-02 03:47:26

标签: python

将MB和KB中给出的值转换为GB和TB的最快方法是什么?

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

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

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

2 个答案:

答案 0 :(得分:6)

假设:

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

首先同意“精确”的含义。由于您的输入是浮点数,因此可以合理地假设“精度”仅限于输入精度。

要计算,首先要转换为基本字节(知道你的实际精度并不比输入精度好):

>>> 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]

然后转换为所需的大小:

>>> 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']

答案 1 :(得分:0)

这是我在网上找到的东西。

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"

来源:http://www.sfentona.net/?p=1965