Last active
March 29, 2021 10:03
-
-
Save elawad/72b707e4b455fe6f63e6a26cdf1bba31 to your computer and use it in GitHub Desktop.
Format file size like macOS
This file contains hidden or 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
function formatSize(size) { | |
const base = 1000; // 1000 or 1024 | |
const kb = base ** 1; | |
const mb = base ** 2; | |
const gb = base ** 3; | |
let num; | |
num = (size / 1).toFixed(0); | |
if (num < base) return Number(num) + ' B'; | |
num = (size / kb).toFixed(0); | |
if (num < base) return Number(num) + ' KB'; | |
num = (size / mb).toFixed(1); | |
if (num < base) return Number(num) + ' MB'; | |
num = (size / gb).toFixed(2); | |
if (num < base) return Number(num) + ' GB'; | |
return Number(num) + ' GB+'; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment