我想最多四舍五入两位小数,但只有在必要时。
输入:
10
1.7777777
9.1
输出:
10
1.78
9.1
如何在JavaScript中执行此操作?
我想最多四舍五入两位小数,但只有在必要时。
输入:
10
1.7777777
9.1
输出:
10
1.78
9.1
如何在JavaScript中执行此操作?
当前回答
我发现这适用于我的所有用例:
const round = (value, decimalPlaces = 0) => {
const multiplier = Math.pow(10, decimalPlaces);
return Math.round(value * multiplier + Number.EPSILON) / multiplier;
};
记住这是ES6。ES5的等效版本很容易编写,所以我不打算添加它。
其他回答
number=(parseInt((number +0.005)*100))/100;
如果要正常舍入(2位小数),请添加0.005
8.123 +0.005=> 8.128*100=>812/100=>8.12
8.126 +0.005=> 8.131*100=>813/100=>8.13
使用类似的方法“parseFloat(parseFlat(value).toFixed(2))”
parseFloat(parseFloat("1.7777777").toFixed(2))-->1.78
parseFloat(parseFloat("10").toFixed(2))-->10
parseFloat(parseFloat("9.1").toFixed(2))-->9.1
根据评论中已给出的答案,链接至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
parseFloat(“1.555”).toFixed(2);//返回1.55而不是1.56。
1.55是绝对正确的结果,因为在计算机中不存在1.555的精确表示。如果读数为1.555,则四舍五入至最接近的值=1.55499999999999994(64位浮点)。将这个数字四舍五入到Fixed(2)得到1.55。
如果输入为1.55499999999999,则此处提供的所有其他功能都会给出故障结果。
解决方案:在扫描前加上数字“5”,将数字舍入(更准确地说,从0开始舍入)。仅当数字真的是浮点(有小数点)时才执行此操作。
parseFloat("1.555"+"5").toFixed(2); // Returns 1.56
与Brian Ustas建议的使用Math.round不同,我更喜欢Math.trunc方法来解决以下问题:
const twoDecimalRound = num => Math.round(num * 100) / 100;
const twoDecimalTrunc = num => Math.trunc(num * 100) / 100;
console.info(twoDecimalRound(79.996)); // Not desired output: 80;
console.info(twoDecimalTrunc(79.996)); // Desired output: 79.99;