Rounding
by timothyausten
JavaScript
// Add a better rounding method to Number.prototype
// http://stackoverflow.com/questions/7783543/javascript-convert-numbers-to-different-formats-or-string-alternative/7783771#7783771
// http://stackoverflow.com/questions/622374/extending-number-prototype-in-javascript-and-the-math-object
// Usage:
// (3.14592).round(2);
// Returns: 3.14
if (!Number.prototype.round) {
Number.prototype.round = function (decimals) {
if (typeof decimals === 'undefined') {
decimals = 0;
}
return Math.round(
this * Math.pow(10, decimals)
) / Math.pow(10, decimals);
};
}
(function () {
var pi = 3.141592,
a = [],
r = [
'Normal rounding of 3.141592:',
'pi.round(2): ' + pi.round(2),
'pi.round(1): ' + pi.round(1),
'pi.round(0): ' + pi.round(0),
'Math.PI: ' + Math.PI,
'Math.PI.round(2): ' + Math.PI.round(2),
'With no parameter:',
'pi.round(0): ' + pi.round(),
'Backward rounding of 3141592:',
'(pi * 100000).round(-1): ' + (pi * 100000).round(-1),
'(pi * 100000).round(-2): ' + (pi * 100000).round(-2),
'(pi * 100000).round(-3): ' + (pi * 100000).round(-3)
];
for (var i = 0; i < r.length; i++) {
a[i] = document.createElement('p');
a[i].innerHTML = r[i];
document.body.appendChild(a[i]);
}
}());