简体   繁体   English

在JavaScript中为Number.prototype添加一个舍入方法

[英]Add a rounding method to Number.prototype in JavaScript

How can I simplify rounding in JavaScript? 如何简化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. toFixed方法效果很好,但是没有向后舍入,它还会返回字符串而不是数字。

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. 扩展Number.prototype。 Numbers in Javascript are a data type that is associated with the built-in object "Number." Javascript中的数字是与内置对象“ Number”关联的数据类型。 Add the following polyfill block: 添加以下polyfill块:

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. 在此之后的任何地方,都可以通过将.round()粘贴到数字的末尾来四舍五入。 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/ 小提琴: http//jsfiddle.net/g2n2fbmq/

Related: 有关:

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM