Add a rounding method to Number.prototype in JavaScript

夙愿已清 提交于 2019-12-11 20:24:30

问题


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

回答1:


Extend Number.prototype. Numbers in Javascript are a data type that is associated with the built-in object "Number." Add the following polyfill block:

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);
    };
}

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:

pi.round(2);

You can also use backward rounding with negative numbers such as:

x = 54321;
x.round(-4);
// 50000

Fiddle: http://jsfiddle.net/g2n2fbmq/

Related:

  • Javascript Convert numbers to different formats or string alternative
  • Extending Number.prototype in javascript and the Math object?
  • Integer prototype


来源:https://stackoverflow.com/questions/27035308/add-a-rounding-method-to-number-prototype-in-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!