Convert Bytes to KB MB GB TB PB EB ZB YB in Javascript Javascript by Rajesh Kumar Sahanee - March 17, 20200 Post Views: 4,913 Hello Friends, today we are going to see how to convert bytes to kb, mb, gb, tb, pb, eb, zb, yb in javascript. The same feature i was required to add in one of my project to convert size of files uploaded on server through media upload feature just like wordpress. As PHP filesize function gives file size in bytes that’s why I was required this function. So, here is the code bytes-to-kb-mb-gb-etc.html bytes-to-kb-mb-gb-etc.html XHTML <!DOCTYPE html> <html> <head> <title>Convert Bytes to KB MB GB TB PB EB ZB YB in Javascript</title> </head> <body style="padding: 10%;"> <input type="number" id="bytes" placeholder="value in bytes"/> <input type="button" id="change" value="Convert"/> <p><strong>Output: </strong><span id="output"></span></p> <script src="https://code.jquery.com/jquery-3.4.1.min.js" crossorigin="anonymous"></script> <script> $("#change").click(function (e) { var bytes = $("#bytes").val(); if (bytes === "") { alert("Please enter value in bytes") return; } $("#output").html(formatBytes(bytes)); }); 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]; } </script> </body> </html> 12345678910111213141516171819202122232425262728293031323334 <!DOCTYPE html><html> <head> <title>Convert Bytes to KB MB GB TB PB EB ZB YB in Javascript</title> </head> <body style="padding: 10%;"> <input type="number" id="bytes" placeholder="value in bytes"/> <input type="button" id="change" value="Convert"/> <p><strong>Output: </strong><span id="output"></span></p> <script src="https://code.jquery.com/jquery-3.4.1.min.js" crossorigin="anonymous"></script> <script> $("#change").click(function (e) { var bytes = $("#bytes").val(); if (bytes === "") { alert("Please enter value in bytes") return; } $("#output").html(formatBytes(bytes)); }); 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]; } </script> </body></html> Output Demo Click Here for Demo Thank you Friends Please don’t forget share if you like it