如何以MB爲單位獲得準確的文件大小?我嘗試這樣做:以兆字節獲取準確的文件大小?
compressed_file_size = File.size("Compressed/#{project}.tar.bz2")/1024000
puts "file size is #{compressed_file_size} MB"
但它切碎了0.9,表明2 MB,而不是2.9 MB
如何以MB爲單位獲得準確的文件大小?我嘗試這樣做:以兆字節獲取準確的文件大小?
compressed_file_size = File.size("Compressed/#{project}.tar.bz2")/1024000
puts "file size is #{compressed_file_size} MB"
但它切碎了0.9,表明2 MB,而不是2.9 MB
嘗試:
compressed_file_size = File.size("Compressed/#{project}.tar.bz2").to_f/2**20
formatted_file_size = '%.2f' % compressed_file_size
一行代碼:
compressed_file_size = '%.2f' % (File.size("Compressed/#{project}.tar.bz2").to_f/2**20)
或:
compressed_file_size = (File.size("Compressed/#{project}.tar.bz2").to_f/2**20).round(2)
%
- 運算符字符串的
更多信息: http://ruby-doc.org/core-1.9/classes/String.html#M000207
BTW:我喜歡 「MIB」,而不是 「MB」 如果我使用BASE2計算(見:http://en.wikipedia.org/wiki/Mebibyte)
嘗試:
compressed_file_size = File.size("Compressed/#{project}.tar.bz2").to_f/1024000
你可能會發現有用的格式化功能(pretty print file size),這裏是我的示例,
def format_mb(size)
conv = [ 'b', 'kb', 'mb', 'gb', 'tb', 'pb', 'eb' ];
scale = 1024;
ndx=1
if(size < 2*(scale**ndx) ) then
return "#{(size)} #{conv[ndx-1]}"
end
size=size.to_f
[2,3,4,5,6,7].each do |ndx|
if(size < 2*(scale**ndx) ) then
return "#{'%.3f' % (size/(scale**(ndx-1)))} #{conv[ndx-1]}"
end
end
ndx=7
return "#{'%.3f' % (size/(scale**(ndx-1)))} #{conv[ndx-1]}"
end
測試出來,
tries = [ 1,2,3,500,1000,1024,3000,99999,999999,999999999,9999999999,999999999999,99999999999999,3333333333333333,555555555555555555555]
tries.each { |x|
print "size #{x} -> #{format_mb(x)}\n"
}
將會產生,
size 1 -> 1 b
size 2 -> 2 b
size 3 -> 3 b
size 500 -> 500 b
size 1000 -> 1000 b
size 1024 -> 1024 b
size 3000 -> 2.930 kb
size 99999 -> 97.655 kb
size 999999 -> 976.562 kb
size 999999999 -> 953.674 mb
size 9999999999 -> 9.313 gb
size 999999999999 -> 931.323 gb
size 99999999999999 -> 90.949 tb
size 3333333333333333 -> 2.961 pb
size 555555555555555555555 -> 481.868 eb
從浮VS INT問題分開 - 是真的1024000恆你想要什麼?通常MB是2^20,即1048576. – 2011-06-02 14:33:01
謝謝你的提示。我在我的代碼中修復了這一點。 – emurad 2011-06-02 14:46:40
根據你想要的完全特性,Rails的'ActionView :: Helpers :: NumberHelper#number_to_human_size'的源代碼是一個很好的參考實現。 http://apidock.com/rails/ActionView/Helpers/NumberHelper/number_to_human_size – captainpete 2013-04-20 10:58:44