Last active
September 12, 2023 04:53
-
-
Save eczn/1aa9b3ed06e37b8cc025f80d23d1bb55 to your computer and use it in GitHub Desktop.
bytes storage units fomatter
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 enum Units { | |
B = 1, | |
KB = 1 * 1024, | |
MB = 1 * 1024 * 1024, | |
GB = 1 * 1024 * 1024 * 1024, | |
TB = 1 * 1024 * 1024 * 1024 * 1024, | |
} | |
const UnitsName = ['B', 'KB', 'MB', 'GB', 'TB']; | |
export function toUnitString(value: number, unitIdx = 0): string { | |
const unitName = UnitsName[unitIdx]; | |
if (unitIdx === (UnitsName.length - 1)) return `${value.toFixed(2)}${unitName}`; | |
// `1023MB` should to be `0.99GB` | |
if (value > 896) return toUnitString(value / 1024, unitIdx + 1); | |
return `${value.toFixed(2)}${unitName}`; | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment