Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bytes to megabytes in ruby

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.

like image 461
Muhambi Avatar asked Jun 11 '15 05:06

Muhambi


1 Answers

I don't want to be a smart-ass, but no one seems to notice the calculation confusion here. 1 megabyte is simply 1000000 byte (google it). The 1024 is an outdated confusion about 10^2 byte which is 1024 kilobyte. Since 1998 this has become known as a kibibyte (wiki) and is now the norm.

That means you should just divide your byte by 1000000 and you're done. I've added some rounding for extra usefulness:

def bytes_to_megabytes (bytes)
    (bytes.to_f / 1000000).round(2)
end
puts bytes_to_megabytes(1153597)  # outputs 1.15
like image 188
leondepeon Avatar answered Oct 21 '22 10:10

leondepeon