Skip to content

Instantly share code, notes, and snippets.

@lmgeorge
Created February 26, 2020 22:03
Show Gist options
  • Save lmgeorge/452c17931e16c79e4c59339db7bd132a to your computer and use it in GitHub Desktop.
Save lmgeorge/452c17931e16c79e4c59339db7bd132a to your computer and use it in GitHub Desktop.
Simple SI unit conversion
const SI = {
UNITS: ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'],
BASE: 1024
}
function calculateFileDisplayLength(bytes){
const units = SI.UNITS
const base = SI.BASE
let magnitude = 0;
let accuracy = 0
let unit = units[magnitude]
let decimal = bytes
if (bytes === 0) {
return '0'
}
if(_.isNil(bytes)){
return ' '
}
if (bytes > base) {
magnitude = Math.floor(Math.log(bytes) / Math.log(base))
if (magnitude < units.length) {
unit = units[magnitude]
decimal = (bytes / Math.pow(base, magnitude))
accuracy = Math.ceil(decimal % 1)
}
}
return `${decimal.toFixed(accuracy)} ${unit}`
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment