Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting accurate file size in megabytes?

Tags:

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

like image 730
emurad Avatar asked Jun 02 '11 14:06

emurad


People also ask

How do you calculate file size in MB?

format("The size of the file: %d bytes", fileSize); These methods will output the size in Bytes. So to get the MB size, you need to divide the file size from (1024*1024).

How do I find the exact file size?

Locate the file or folder whose size you would like to view. Click the file or folder. Press Command + I on your keyboard. A window opens and shows the size of the file or folder.


2 Answers

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)

like image 158
asaaki Avatar answered Oct 14 '22 23:10

asaaki


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.

like image 42
cam Avatar answered Oct 15 '22 00:10

cam