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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 |
<!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
Comments