Javascript Converting Bytes

How To Convert Bytes to KB, MB, GB, TB Format in javascript. Converting bytes to human readable values KB, MB, GB, TB

buttons Examples:
Demo Byte Converter
1

JavaScript Converting Bytes

JavaScript
function byte_format(bytes) {
    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;
  var preview_size = document.getElementById("preview-size");
  let result = byte_format(byte);
  preview_size.innerHTML= result
}
</script>