Created
November 26, 2025 08:15
-
-
Save denwwer/c09c9731fcb064372a3d1f4fa199d420 to your computer and use it in GitHub Desktop.
This file contains hidden or 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 interface Bytes { | |
| value: number; | |
| unit: string; | |
| } | |
| /** | |
| * Convert a number of bytes into a human-readable string (e.g. "1.23 MB") | |
| * @param bytes | |
| * @param decimals How many decimal places to include | |
| */ | |
| export default function formatBytes(bytes, decimals = 2): Bytes { | |
| if (!bytes) return { value: 0, unit: '' }; | |
| const k = 1024; // or 1000 for decimal units | |
| const dm = decimals < 0 ? 0 : decimals; | |
| const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB']; | |
| const i = Math.floor(Math.log(bytes) / Math.log(k)); | |
| return { | |
| value: parseFloat((bytes / Math.pow(k, i)).toFixed(dm)), | |
| unit: sizes[i] | |
| }; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment