Skip to content

Instantly share code, notes, and snippets.

@cmc19
Last active May 17, 2024 03:10
Show Gist options
  • Save cmc19/9670351 to your computer and use it in GitHub Desktop.
Save cmc19/9670351 to your computer and use it in GitHub Desktop.
//adapted from https://github.com/kapouer/bytes.js
var util = util || {};
(function (util) {
function bytes(size) {
if ('number' == typeof size) return convert(size);
var parts = size.match(/^(\d+(?:\.\d+)?) *(kb|mb|gb)$/i),
n = parseFloat(parts[1]),
type = parts[2].toLowerCase();
var map = {
kb: 1 << 10,
mb: 1 << 20,
gb: 1 << 30
};
return map[type] * n;
/**
* convert bytes into string.
*
* @param {Number} b - bytes to convert
* @return {String}
* @api public
*/
function convert(b) {
var gb = 1 << 30,
mb = 1 << 20,
kb = 1 << 10;
if (b >= gb) return (Math.round(b / gb * 100) / 100) + 'GB';
if (b >= mb) return (Math.round(b / mb * 100) / 100) + 'MB';
if (b >= kb) return (Math.round(b / kb * 100) / 100) + 'KB';
return b + 'B';
}
};
util.bytes = bytes;
})(util);
util.bytes(1024* 1024 * 1.5) // => 1.5MB
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment