获取准确的文件大小(兆字节)?

时间:2011-06-02 14:27:47

标签: ruby

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

4 个答案:

答案 0 :(得分:29)

尝试:

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:如果我使用base2计算,我更喜欢“MiB”而不是“MB”(参见:http://en.wikipedia.org/wiki/Mebibyte

答案 1 :(得分:8)

你正在进行整数除法(它会丢弃小数部分)。尝试除以1024000.0,因此ruby知道你想做浮点数学。

答案 2 :(得分:2)

尝试:

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

答案 3 :(得分: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