我想最多四舍五入两位小数,但只有在必要时。

输入:

10
1.7777777
9.1

输出:

10
1.78
9.1

如何在JavaScript中执行此操作?


当前回答

所有浏览器和精度的通用答案:

function round(num, places) {
    if(!places) {
        return Math.round(num);
    }

    var val = Math.pow(10, places);
    return Math.round(num * val) / val;
}

round(num, 2);

其他回答

一个简单的通用解决方案

常量舍入=(n,dp)=>{常量h=+('1'.padEnd(dp+1,'0'))//10或100或1000等return数学舍入(n*h)/h}console.log(“圆形(2.3454,3)”,圆形console.log(“圆形(2.3456,3)”,圆形(2.34563))//2.346console.log('圆形(2.3456,2)',圆形(2.34562))//2.35

或者只使用具有相同签名的Lodash圆-例如,_.round(2.3456,2)

一个简单的解决方案是,如果你想四舍五入,可以使用Lodash的ceil函数。。。

_.round(6.001, 2)

给出6

_.ceil(6.001, 2);

给出6.01

_.ceil(37.4929, 2);

给出37.5

_.round(37.4929, 2);

给出37.49

在Node.js环境中,我只使用roundTo模块:

const roundTo = require('round-to');
...
roundTo(123.4567, 2);

// 123.46

根据评论中已给出的答案,链接至http://jsfiddle.net/AsRqx/,下面的一个对我来说很好。

function C(num)
{
    return +(Math.round(num + "e+2") + "e-2");
}

function N(num, places)
{
    return +(Math.round(num + "e+" + places) + "e-" + places);
}

C(1.005);

N(1.005, 0);
N(1.005, 1); // Up to 1 decimal places
N(1.005, 2); // Up to 2 decimal places
N(1.005, 3); // Up to 3 decimal places

有一种解决方案适用于所有数字。试试看。表达式如下所示。

Math.round((num + 0.00001) * 100) / 100. 

Try Below Ex:

Math.round((1.005 + 0.00001) * 100) / 100 
Math.round((1.0049 + 0.00001) * 100) / 100

我最近测试了所有可能的解决方案,并在尝试了近10次后最终得出了结果。

这是计算过程中出现的问题的屏幕截图,

.

转到金额字段。它几乎无限地回归。我尝试了toFixed()方法,但它在某些情况下不起作用(例如,尝试使用pi),最后导出了上面给出的解决方案。