2011-06-02 68 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