Created
February 26, 2020 22:03
-
-
Save lmgeorge/452c17931e16c79e4c59339db7bd132a to your computer and use it in GitHub Desktop.
Simple SI unit conversion
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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