Byte Conversion

Takes a value in Bytes and converts it to a size with specified precision

by mmansion

HTML

<h3>Convert Bytes to Sizes</h3>
<input id="bytes" type="text" />
<button id="btn" type="button">Convert</button> 
<hr>
<p id="output" style="background:lightgray">
    output
</p>

JavaScript

/**
 * Convert number of bytes into human readable format
 *
 * @param integer bytes     Number of bytes to convert
 * @param integer precision Number of digits after the decimal separator
 * @return string
 */

function bytesToSize(bytes, precision) {
    var sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB'];
    var posttxt = 0;
    while (bytes >= 1024) {
        posttxt++;
        bytes = bytes / 1024;
    }
    return Number(bytes).toFixed(precision) + " " + sizes[posttxt];
}

//--------------------------------------------------------------
var output = document.getElementById("output");
var bytes = document.getElementById("bytes");;

document.getElementById("btn").onclick = function() {
    var value = parseInt(bytes.value);
    if(!isNaN(value)) {
     console.log(bytesToSize(value, 2));
    } else {
      alert("enter a valid number");        
    }
}