Skip to content

Latest commit

 

History

History
22 lines (18 loc) · 546 Bytes

format-file-size.md

File metadata and controls

22 lines (18 loc) · 546 Bytes
title description author tags
Format File Size
Converts bytes into human-readable file size format.
jjcantu
format,size
function formatFileSize(bytes) {
  if (bytes === 0) return '0 Bytes';
  
  const k = 1024;
  const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB'];
  const i = Math.floor(Math.log(bytes) / Math.log(k));
  
  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
}

// Usage:
console.log(formatFileSize(1234)); // Output: "1.21 KB"
console.log(formatFileSize(1234567)); // Output: "1.18 MB"