Last Updated: February 25, 2016
·
799
· bezhermoso

Round float by `n` decimal places in Javascript

If you need to round floats by n decimal places i.e. rounding 3.1415926 to 4 decimal places = 3.1416, try this function:

Math.roundBy = function (decimalPlaces, n) {
    var scale = Math.pow(10, decimalPlaces);
    return Math.round(scale * n) / scale;
};

Math.roundBy(4, Math.PI); // 3.1416

Note the decimal place argument is first. This makes the function curry-friendly:

roundBy2 = Math.round.curry(2);
roundBy2(someNum);

See https://coderwall.com/p/tryjpq/currying-javascript-functions for more about currying.