2011-06-02 66 views
18

如何以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

+5

從浮VS INT問題分開 - 是真的1024000恆你想要什麼?通常MB是2^20,即1048576. – 2011-06-02 14:33:01

+0

謝謝你的提示。我在我的代碼中修復了這一點。 – emurad 2011-06-02 14:46:40

+0

根據你想要的完全特性,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

回答

26

嘗試:

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) 

0123在 % - 運算符字符串的

更多信息: http://ruby-doc.org/core-1.9/classes/String.html#M000207


BTW:我喜歡 「MIB」,而不是 「MB」 如果我使用BASE2計算(見:http://en.wikipedia.org/wiki/Mebibyte

7

你做的整數除法(其中下降小數部分)。嘗試除以1024000.0,所以紅寶石知道你想做浮點數學。

+0

我甚至沒有使用Ruby,那正是我想要建議的。 – JAB 2011-06-02 14:31:23

+0

這也是。這是給我2.8679921875 MB我只想要2.86 MB – emurad 2011-06-02 14:46:13

+0

只是呼籲(3) – 0112 2014-11-05 20:04:21

2

嘗試:

compressed_file_size = File.size("Compressed/#{project}.tar.bz2").to_f/1024000 
+0

這就是給我2.8679921875 MB我只想2.86 MB – emurad 2011-06-02 14:45:57

+2

您可以使用compressed_file_size.round(2)或'.2f'%compressed_file_size輸出 – Hck 2011-06-02 14:50:32

+0

我didn在輸出中不會得到'.2f'%compressed_file_size。請澄清。 – emurad 2011-06-02 14:56:50

1

你可能會發現有用的格式化功能(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