乐闻世界logo
搜索文章和话题

What is the correct way to convert size in bytes to KB, MB, GB in JavaScript

1个答案

1
  1. Define conversion bases:
  • 1 KB (kilobyte) = 1024 bytes
  • 1 MB (megabyte) = 1024 KB
  • 1 GB (gigabyte) = 1024 MB
  1. Create a function for conversion: We can write a function that takes byte size as input and returns the corresponding KB, MB, or GB.
javascript
function 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:

javascript
console.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 k representing the multiplier for each unit (1024).
  • The sizes array lists the possible size units.
  • We use Math.log and Math.pow to convert bytes to other units, and toFixed to 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 回复

你的答案