Last Updated: February 25, 2016
·
1.03K
· 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.

Have a fresh tip? Share with Coderwall community!

Post
Post a tip
Did you know?

JavaScript on a page runs with the privileges of that origin. One altered library, tag manager, or snippet can read inputs, change what people see, and call your APIs as the user.

Security insights from Cside