Ruby-on-rails – Bytes to megabytes in ruby

rubyruby-on-rails

In javascript (or coffeescript), I have the following function:

bytesToMegabytes = (bytes) ->
  return Math.round((b/1024/1024) * 100) / 100

I'm trying to recreate it in ruby. I have:

def bytes_to_megabytes (bytes)
    (((bytes.to_i/1024/1024) * 100) / 100).round
end

But this rounds differently? For example, 1153597 becomes 1 in the ruby code.

Best Solution

Try:

def bytes_to_megabytes (bytes)
    bytes / (1024.0 * 1024.0) 
end
bytes_to_megabytes(1153597)
#=> 1.1001558303833008

You can make CONSTANT variable like

MEGABYTES = 1024.0 * 1024.0
def bytes_to_megabytes (bytes)
    bytes / MEGABYTES
end
bytes_to_megabytes(1153597)
#=> 1.1001558303833008

Now make you clear about to_i and round,

But this rounds differently? For example, 1153597 becomes 1 in the ruby code.

to_i method take only decimal part it does not roundup the number for that you have to convert to float then roundup

 > "148.68".to_i
 #=> 148 
 > "148.68".to_f.round
 #=> 149 

As Stefen's comment : In Rails You can do simply like this:

 > 1153597 / 1.0.megabyte
 #=> 1.1001558303833008 
 > (1153597 / 1.0.megabyte).round
 #=> 1

For more details of megabyte method Numeric#megabyte