Skip to content

Instantly share code, notes, and snippets.

@Wardrop
Last active June 22, 2017 04:46
Show Gist options
  • Save Wardrop/b01ffcd274221e826d83c5b3943a5ba2 to your computer and use it in GitHub Desktop.
Save Wardrop/b01ffcd274221e826d83c5b3943a5ba2 to your computer and use it in GitHub Desktop.
// Formats the given byte value into a human readable form.
//
// Accepts four optional arguments that control the output format:
// as_bits: If true, converts the given byte value to bits and adjusts the suffix accordingly. Defaults to false.
// binary: If true, calculates order of magnitude as base 2 (binary) instead of base 10 (decimal). Defaults to true.
// full_suffix: If true, uses full suffix names such as "Megabyte", otherwise uses abbreviations like "MB" or "Mib". Defaults to false.
// precision: The number of decimal points to include in the output. Trailing zero's are removed. Defaults to 2.
function formatBytes (bytes, as_bits, binary, full_suffix, precision) {
as_bits = typeof as_bits !== 'undefined' ? as_bits : false;
binary = typeof binary !== 'undefined' ? binary : true;
full_suffix = typeof full_suffix !== 'undefined' ? full_suffix : false;
precision = typeof precision !== 'undefined' ? precision : 2;
var suffixes = ['Kilo', 'Mega', 'Giga', 'Tera', 'Peta', 'Exa', 'Zetta', 'Yotta']
if (binary) {
suffixes = suffixes.map(function (v) { return v[0]+'ibi' })
}
var abbreviations = suffixes.map(function(v) {
return v[0] + (as_bits ? 'b' : 'B')
})
var base = 1000
if (binary) {
var base = 1024
abbreviations = abbreviations.map(function (v) { return v[0] + "i" + v[1] })
}
suffixes.unshift("")
abbreviations.unshift(as_bits ? 'bits' : 'bytes')
if (as_bits) {
suffixes = suffixes.map(function (v) { return v += 'bits' })
bytes *= 8
} else {
suffixes = suffixes.map(function (v) { return v += 'bytes' })
}
var exponent = bytes == 0 ? 0 : Math.floor(Math.log(bytes) / Math.log(base))
var suffix = full_suffix ? suffixes[exponent] : abbreviations[exponent]
var value = (bytes / Math.pow(base, exponent)).toFixed(precision).replace(/[.0]+$/, '')
return value + " " + suffix
}
// Examples
formatBytes(2039495402, true, true)
formatBytes(2039495402, true, false)
formatBytes(2039495402, false, false)
formatBytes(2039495402, false, true)
formatBytes(2039495402, true, true, true)
formatBytes(2039495402, true, false, true)
formatBytes(2039495402, false, false, true)
formatBytes(2039495402, false, true, true)
formatBytes(96, true, true)
formatBytes(96, true, false)
formatBytes(96, false, false)
formatBytes(96, false, true)
formatBytes(96, true, true, true)
formatBytes(96, true, false, true)
formatBytes(96, false, false, true)
formatBytes(96, false, true, true)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment