Skip to content

Instantly share code, notes, and snippets.

@elawad
Last active March 29, 2021 10:03
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save elawad/72b707e4b455fe6f63e6a26cdf1bba31 to your computer and use it in GitHub Desktop.
Save elawad/72b707e4b455fe6f63e6a26cdf1bba31 to your computer and use it in GitHub Desktop.
Format file size like macOS
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