Skip to content

Instantly share code, notes, and snippets.

@seven1m
Created November 12, 2009 16:45
Show Gist options
  • Save seven1m/233053 to your computer and use it in GitHub Desktop.
Save seven1m/233053 to your computer and use it in GitHub Desktop.
matching ruby and javascript methods for formatting bytes in human readable format
function number_to_human_size(size) {
if(size < 1024)
return size + ' bytes';
else if(size < 1024.0 * 1024.0)
return (size / 1024.0).toFixed(1) + ' KiB'
else if(size < 1024.0 * 1024.0 * 1024.0)
return (size / 1024.0 / 1024.0).toFixed(1) + ' MiB'
else
return (size / 1024.0 / 1024.0 / 1024.0).toFixed(1) + ' GiB';
}
def number_to_human_size(size)
if size < 1024
"#{size} bytes"
elsif size < 1024.0 * 1024.0
"%.01f KiB" % (size / 1024.0)
elsif size < 1024.0 * 1024.0 * 1024.0
"%.01f MiB" % (size / 1024.0 / 1024.0)
else
"%.01f GiB" % (size / 1024.0 / 1024.0 / 1024.0)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment