Created
February 26, 2020 13:34
-
-
Save sylvainpolletvillard/2bba6ef84917aa9456b3eb898030e49b to your computer and use it in GitHub Desktop.
formatters.js
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
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