- Define conversion bases:
- 1 KB (kilobyte) = 1024 bytes
- 1 MB (megabyte) = 1024 KB
- 1 GB (gigabyte) = 1024 MB
- Create a function for conversion: We can write a function that takes byte size as input and returns the corresponding KB, MB, or GB.
javascriptfunction formatBytes(bytes, decimals = 2) { if(bytes === 0) return '0 Bytes'; const k = 1024; 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 parseFloat((bytes / Math.pow(k, i)).toFixed(dm)) + ' ' + sizes[i]; }
Usage Examples: Suppose we have a file size of 123456 bytes, and we want to get the size in other units. We can call the function as follows:
javascriptconsole.log(formatBytes(123456)); // Output "120.56 KB" console.log(formatBytes(123456, 0)); // Output "121 KB" console.log(formatBytes(987654321)); // Output "942.08 MB" console.log(formatBytes(123456789012)); // Output "114.98 GB"
Explanation:
The function formatBytes takes two parameters: bytes (the byte count) and decimals (the number of decimal places to include in the result, defaulting to 2).
- We define a constant
krepresenting the multiplier for each unit (1024). - The
sizesarray lists the possible size units. - We use
Math.logandMath.powto convert bytes to other units, andtoFixedto format the result to the specified decimal places. - Finally, the function returns the converted value along with the corresponding unit.
This method is flexible for scenarios requiring byte unit conversion, such as in file management systems or web applications displaying file sizes.
2024年6月29日 12:07 回复