我想最多四舍五入两位小数,但只有在必要时。
输入:
10
1.7777777
9.1
输出:
10
1.78
9.1
如何在JavaScript中执行此操作?
我想最多四舍五入两位小数,但只有在必要时。
输入:
10
1.7777777
9.1
输出:
10
1.78
9.1
如何在JavaScript中执行此操作?
当前回答
根据评论中已给出的答案,链接至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
其他回答
一个简单的通用解决方案
常量舍入=(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)
它可能对你有用,
Math.round(num * 100)/100;
了解toFixed和round之间的区别。您可以查看Math.round(num)vs num.toFixed(0)和浏览器不一致性。
最简单的方法是使用toFixed,然后使用Number函数去除尾随零:
const number = 15.5;
Number(number.toFixed(2)); // 15.5
const number = 1.7777777;
Number(number.toFixed(2)); // 1.78
如果使用的是Lodash库,可以使用Lodash的舍入方法,如下所示。
_.round(number, precision)
例如:
_.round(1.7777777, 2) = 1.78
+(10).toFixed(2); // = 10
+(10.12345).toFixed(2); // = 10.12
(10).toFixed(2); // = 10.00
(10.12345).toFixed(2); // = 10.12