JavaScript Convert bytes to human-readable string
Given the size of a file(in Bytes), The task is to convert it into human-readable form using JavaScript. Here are few methods discussed.
Example 1: This example converts the file Size(in Bytes) into human-readable form. It shows the values in decimal and for less than 1024 Bytes, it remains in Bytes.
html
< h1 style = "color:green;" > GeeksforGeeks </ h1 > < p id = "GFG_UP" > </ p > < button onclick = "GFG_Fun()" > click here </ button > < p id = "GFG_DOWN" > </ p > < script > var up = document.getElementById('GFG_UP'); up.innerHTML = 'Convert bytes to human readable form'; var down = document.getElementById('GFG_DOWN'); size = function(bytes) { if (bytes == 0) { return "0.00 B"; } var e = Math.floor(Math.log(bytes) / Math.log(1024)); return (bytes / Math.pow(1024, e)).toFixed(2) + ' ' + ' KMGTP'.charAt(e) + 'B'; } function GFG_Fun() { var bytes = 2007777777770; down.innerHTML = bytes + " bytes = " + size(bytes); } </ script > |
Output:

JavaScript Convert bytes to human-readable string
Example 2: This example converts the file Size(in Bytes) into human-readable form. It shows the values in decimal and for less than 1024 Bytes, it remains in Bytes. But, with a different approach.
html
< h1 style = "color:green;" > GeeksForGeeks </ h1 > < p id = "GFG_UP" > </ p > < button onclick = "GFG_Fun()" > click here </ button > < p id = "GFG_DOWN" > </ p > < script > var up = document.getElementById('GFG_UP'); up.innerHTML = 'Convert bytes to human readable form'; var down = document.getElementById('GFG_DOWN'); function getSize(size) { var sizes = [' Bytes', ' KB', ' MB', ' GB', ' TB', ' PB', ' EB', ' ZB', ' YB']; for (var i = 1; i < sizes.length ; i++) { if (size < Math.pow(1024, i)) return (Math.round((size / Math.pow( 1024, i - 1)) * 100) / 100) + sizes[i - 1]; } return size; } function GFG_Fun() { var bytes = 1024 ; down.innerHTML = bytes + " bytes = " + getSize(bytes); } </script> |
Output:

JavaScript Convert bytes to human-readable string
Please Login to comment...