Created
August 25, 2025 19:01
-
-
Save nash403/189f000752047d49b0f0b75fbf82b5f1 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 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