Skip to main content

Round a given number value to the specified precision.

/**
 * Round a given value to the specified precision
 *
 * Difference to Math.round() is that there will be appended Zeros to the end if
 * the precision is not reached (0.1 gets rounded to 0.100 when precision is set
 * to 3)
 *
 * @param {Number} x value to round
 * @param {Number} n precision
 * @return {String}
 */
function round(x, n) {
    var e = 0,
        k = "";
    if (n < 0 || n > 14) {
        return 0;
    }
    if (n === 0) {
        return Math.round(x);
    } else {
        e = Math.pow(10, n);
        k = (Math.round(x * e) / e).toString();
        if (k.indexOf(".") === -1) {
            k += ".";
        }
        k += e.toString().substring(1);
        return k.substring(0, k.indexOf(".") + n + 1);
    }
}