Skip to content

Instantly share code, notes, and snippets.

@nash403
Created August 25, 2025 19:01
Show Gist options
  • Save nash403/189f000752047d49b0f0b75fbf82b5f1 to your computer and use it in GitHub Desktop.
Save nash403/189f000752047d49b0f0b75fbf82b5f1 to your computer and use it in GitHub Desktop.
export const formatFileSize = (bytes, fSExt = ['Bytes', 'KB', 'MB', 'GB']) => {
// fSExt is an Array of unit labels
let i = 0 // Index to track which unit to use
while (bytes > 900) { // While the size is bigger than 900 in the current unit
bytes /= 1024 // Convert to the next bigger unit
i++ // Move to the next unit in the array
}
return (Math.round(bytes * 100) / 100) + ' ' + fSExt[i] // Round to 2 decimal places and append unit
}
// formatFileSize(500) // → "500 Bytes"
// formatFileSize(1024) // → "1 KB"
// formatFileSize(1536000) // → "1.46 MB"
// formatFileSize(1073741824) // → "1 GB"
// formatFileSize(950) // → "0.93 KB" // Switches before hitting 1 KB because of the 900 threshold
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment