Converts a number in units of bytes to a human-readable form. - Node.js Number

Node.js examples for Number:Format

Description

Converts a number in units of bytes to a human-readable form.

Demo Code



// Converts a number in units of bytes to a human-readable form.
// @param bytes - the number to convert, in bytes
// @param decimalPlaces - the number of decimal places, default is 0
// @return A string with a human-readable representation of the number
humanizeBytes: function(bytes, decimalPlaces) {
    function trunc(n) {
        return n.toFixed(decimalPlaces || 0);
    }//www .  j a  va  2 s. c o m
    if (bytes < 1024.0) {
        return bytes + " B";
    } else if (bytes < 1024.0 * 1024.0) {
        return trunc(bytes / 1024.0) + " KB";
    } else if (bytes < 1024.0 * 1024.0 * 1024.0) {
        return trunc(bytes / (1024.0 * 1024.0)) + " MB";
    } else if (bytes < 1024.0 * 1024.0 * 1024.0 * 1024.0) {
        return trunc(bytes / (1024.0 * 1024.0 * 1024.0)) + " GB";
    } else {
        return trunc(bytes / (1024.0 * 1024.0 * 1024.0 * 1024.0)) + " TB";
    }
},

Related Tutorials