在 JavaScript 中为 Number.prototype 添加一个舍入方法 [英] Add a rounding method to Number.prototype in JavaScript

查看:55
本文介绍了在 JavaScript 中为 Number.prototype 添加一个舍入方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何简化 JavaScript 中的舍入?我希望我能以面向对象的方式更优雅地完成它.toFixed 方法运行良好,但没有向后舍入,它也返回一个字符串而不是数字.

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.Javascript 中的数字是一种与内置对象数字"相关联的数据类型.添加以下 polyfill 块:

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

在此之后的任何地方,您都可以通过将 .round() 粘贴到数字末尾来对数字进行舍入.它有一个确定小数位数的可选参数.例如:

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

小提琴:http://jsfiddle.net/g2n2fbmq/

相关:

这篇关于在 JavaScript 中为 Number.prototype 添加一个舍入方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆