If you would like to convert the amount of bytes (or bits) into the corresponding measure when the size is a kilobyte or bigger (or a kilobit or bigger) you can use the following JavaScript function:

Here are some examples of using it:

// Convert bytes
console.log(suffixFileSize(1023));    // 1023 B
console.log(suffixFileSize(8192));    // 8 KB
console.log(suffixFileSize(1048576)); // 1 MB

// Convert bits
console.log(suffixFileSize(1023, true));    // 1.02 kb
console.log(suffixFileSize(8192, true));    // 8.19 kb
console.log(suffixFileSize(1048576, true)); // 1.05 Mb

If you would like to know how this function, what it does is uses logarithm to determine when to go from one measure to the next. Feel free to use this function in your own project. Happy coding!!! šŸ˜Ž


Leave a Reply

Your email address will not be published. Required fields are marked *