How can I simplify rounding in JavaScript? I wish that I could do it in a more elegantly in an object-oriented manner. The method toFixed works well, but does not have backward rounding and it also returns a string and not a number.
pi.toFixed(2).valueOf();
// 3.14
As it is, rounding is a bit of a tangle because I have to use:
pi = Math.round(pi * 100) / 100;
// 3.14
It would be much nicer instead just to stick a method to the end of a variable, such as:
pi.round(2);
// 3.1r
Extend Number.prototype. Numbers in Javascript are a data type that is associated with the built-in object "Number." Add the following polyfill block:
Anywhere after this, you can round numbers by sticking .round() to the end of them. It has one optional parameter that determines the number of decimals. For example:
You can also use backward rounding with negative numbers such as:
Fiddle: http://jsfiddle.net/g2n2fbmq/
Related: