emurad
emurad

Reputation: 3578

Getting accurate file size in megabytes?

How can I get the accurate file size in MB? I tried this:

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

puts "file size is #{compressed_file_size} MB"

But it chopped the 0.9 and showed 2 MB instead of 2.9 MB

Upvotes: 27

Views: 40360

Answers (4)

ChuckCottrill
ChuckCottrill

Reputation: 4444

You might find a formatting function useful (pretty print file size), and here is my example,

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

Test it out,

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"
}

Which produces,

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

Upvotes: 1

asaaki
asaaki

Reputation: 2000

Try:

compressed_file_size = File.size("Compressed/#{project}.tar.bz2").to_f / 2**20
formatted_file_size = '%.2f' % compressed_file_size

One-liner:

compressed_file_size = '%.2f' % (File.size("Compressed/#{project}.tar.bz2").to_f / 2**20)

or:

compressed_file_size = (File.size("Compressed/#{project}.tar.bz2").to_f / 2**20).round(2)

Further information on %-operator of String: http://ruby-doc.org/core-1.9/classes/String.html#M000207


BTW: I prefer "MiB" instead of "MB" if I use base2 calculations (see: http://en.wikipedia.org/wiki/Mebibyte)

Upvotes: 37

Hck
Hck

Reputation: 9167

Try:

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

Upvotes: 4

cam
cam

Reputation: 14222

You're doing integer division (which drops the fractional part). Try dividing by 1024000.0 so ruby knows you want to do floating point math.

Upvotes: 10

Related Questions