Skip to content

Instantly share code, notes, and snippets.

@sylvainpolletvillard
Created February 26, 2020 13:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sylvainpolletvillard/2bba6ef84917aa9456b3eb898030e49b to your computer and use it in GitHub Desktop.
Save sylvainpolletvillard/2bba6ef84917aa9456b3eb898030e49b to your computer and use it in GitHub Desktop.
formatters.js
export const formatBytes = (precision = 2) => bytes => {
if (typeof bytes !== "number") return bytes
if (bytes === 0) return '0 Bytes';
const k = 1024;
const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
const i = Math.floor(Math.log(bytes) / Math.log(k));
return parseFloat((bytes / Math.pow(k, i)).toPrecision(precision)) + ' ' + sizes[i];
}
export const formatNumber = (decimals = 2) => number => {
if (typeof number !== "number") return number
return number.toLocaleString({
style: "compact",
maximumFractionDigits: decimals
})
}
export const formatPercentage = (decimals = 2) => pc => {
if (typeof pc !== "number") return pc
return pc.toFixed(decimals) + ' %'
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment