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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With