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

0 Comments
Demo Byte Converter:
Demo
1

Converting Bytes Function

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
<div id="preview-size"></div>
<input type="number" id="byte" value="1024">
<button id="convert-byte">Convert</button>

<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>
0 comments
Leave a Reply
hostinger