Skip to content

Instantly share code, notes, and snippets.

@lamchau
Last active October 31, 2015 19:26
Show Gist options
  • Save lamchau/cc0d9ad0da384abbb07b to your computer and use it in GitHub Desktop.
Save lamchau/cc0d9ad0da384abbb07b to your computer and use it in GitHub Desktop.
function humanizeBytes(bytes, si) {
unit = si ? 1e3 : 1024;
var byteSuffix = (si ? 'b' : 'B');
if (bytes < unit) {
return bytes + byteSuffix;
}
var modifier = Math.floor(Math.log(bytes) / Math.log(unit));
var prefix = (si ? 'kMGTPEZ' : 'KMGTPEZ')[modifier - 1];
if (!si) {
prefix += 'i';
}
return (bytes / Math.pow(unit, modifier)) + ' ' + prefix + byteSuffix;
}
import math
def human_readable(bytes, si = True):
unit = 1e3 if si else 1024
if bytes < unit:
return '%.1f %s' % (bytes, 'B')
modifier = math.floor(math.log(bytes) / math.log(unit))
pre = ('kMGTPEZ' if si else 'KMGTPEZ')[modifier - 1]
if not si:
pre += 'i'
return '%.1f %sB' % (bytes / math.pow(unit, modifier), pre)
sizes = list(map(lambda x: 1024 * math.pow(10, x), range(0, 10)))
for x in sizes: print(human_readable(x))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment