Convert bytes to megabytes

by on February 6, 2007

In one of my projects, I need to find the file-size in megabytes again and again. This simple method helps me to convert the size of a file in bytes to megabytes. This is useful for very large files.

MEGABYTE = 1024.0 * 1024.0
def bytesToMeg bytes
  bytes /  MEGABYTE
end

# big file
len = File.size("Dreamweaver8-en.exe")
puts len.to_s + ' bytes'  # displays 62651176 bytes
puts bytesToMeg(len).to_s + ' MB'  # displays 59.7488174438477 MB

One of the uses for PDF conversion is that by going through the process of converting PDF to Word you’ll have a more easily editable document than if you didn’t do PDF conversion and tried to edit a PDF file.

The program code is pretty obvious and as you can see the method uses division. However, it is best to wrap this functionality in a method.

Technorati Tags: ,

Posted by Satish Talim

Buzz Follow me on Twitter to communicate and stay connected

{ 3 comments… read them below or add one }

zimbatm February 6, 2007 at 3:02 pm

Or use ruby-units :

require ‘units’
# big file
len = File.size(“Dreamweaver8-en.exe”)
puts len.to_unit(‘B’).to(‘MB’) # same here

Reply

satish February 6, 2007 at 3:43 pm

I guess you are talking about this?
http://ruby-units.rubyforge.org/ruby-units/
I did a gem install ruby-units, but the program that you mentioned did not work? Am I making a mistake somewhere?

Reply

Satish Talim February 14, 2007 at 2:59 pm

The following worked -

require ‘ruby-units’
# big file
len = File.size(“Dreamweaver8-en.exe”)
puts len.to_unit(‘B’).to(‘MB’)

Reply

Leave a Comment

Previous post:

Next post: