JavaScript Converting Byte To KB MB

How To Convert Bytes to KB, MB, GB, TB Format in JavaScript. This function Converting bytes to human readable values Kilobyte, Megabyte, Gigabyte, Terabyte

JavaScript Converting Bytes

JavaScript
function byte_format(bytes) {
    bytes = bytes.toString().replace(/[^0-9.]/g, '');
    var sizes = ["B", "KB", "MB", "GB", "TB"];
    bytes = parseInt(bytes);
    if (bytes <= 0 || isNaN(bytes)) return "0 B";
    var i = Math.floor(Math.log(bytes) / Math.log(1024));
    return Math.round(bytes / Math.pow(1024, i), 2) + ' ' + sizes[i];
}
Usage
HTML
byte <input type="number" id="byte" value="1024">
<button id="convert-byte">Convert</button>
<div id="preview-size"></div>

<script>
document.getElementById("convert-byte").onclick = function(){
  let byte = document.getElementById("byte").value;
  let result = byte_format(byte);
  document.getElementById("preview-size").innerHTML= result
}
</script>