Created
March 18, 2024 11:38
-
-
Save gynekolog/5ea89f25d68fa477f971c683a4920f49 to your computer and use it in GitHub Desktop.
Typescript To Convert Bytes To MB, KB, Etc
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 function convertBytes(bytes: number, options: { useBinaryUnits?: boolean; decimals?: number } = {}): string { | |
const { useBinaryUnits = false, decimals = 2 } = options; | |
if (decimals < 0) { | |
throw new Error(`Invalid decimals ${decimals}`); | |
} | |
const base = useBinaryUnits ? 1024 : 1000; | |
const units = useBinaryUnits | |
? ["Bytes", "KiB", "MiB", "GiB", "TiB", "PiB", "EiB", "ZiB", "YiB"] | |
: ["Bytes", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"]; | |
const i = Math.floor(Math.log(bytes) / Math.log(base)); | |
return `${(bytes / Math.pow(base, i)).toFixed(decimals)} ${units[i]}`; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Test: