Skip to content

Instantly share code, notes, and snippets.

@denwwer
Created November 26, 2025 08:15
Show Gist options
  • Select an option

  • Save denwwer/c09c9731fcb064372a3d1f4fa199d420 to your computer and use it in GitHub Desktop.

Select an option

Save denwwer/c09c9731fcb064372a3d1f4fa199d420 to your computer and use it in GitHub Desktop.
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