Skip to content

Instantly share code, notes, and snippets.

@eczn
Last active September 12, 2023 04:53
Show Gist options
  • Save eczn/1aa9b3ed06e37b8cc025f80d23d1bb55 to your computer and use it in GitHub Desktop.
Save eczn/1aa9b3ed06e37b8cc025f80d23d1bb55 to your computer and use it in GitHub Desktop.
bytes storage units fomatter
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