乘法得出近似结果

时间:2017-06-23 08:54:13

标签: javascript

嗯我在客户端有一个问题,然后在后端验证,由于这个问题验证失败。以下是上一个问题Javascript and C# rounding hell

所以我正在做的是:

在客户端:

I have 2 numbers: 50 and 2.3659
I multiply them: 50 * 2.3659  //118.29499999999999
Round to 2 decimal places: kendo.toString(50 * 2.3659, 'n2') //118.29

在后端(C#):

I am doing the same: 50 and 2.3659
I multiply them: 50 * 2.3659  //118.2950
Round to 2 decimal places: Math.Round(50 * 2.3659, 2) //118.30

验证失败了。我可以在客户端做点什么吗?

3 个答案:

答案 0 :(得分:0)

Haven没有对此进行过广泛的测试,但下面的功能应该模仿“MidPointToEven”。四舍五入:



function roundMidPointToEven(d, f){		
    f = Math.pow(10, f || 0);  // f = decimals, use 0 as default
    let val = d * f, r = Math.round(val); 
    if(r & 1 == 1 && Math.sign(r) * (Math.round(val * 10) % 10) === 5)
    	r +=  val > r ? 1 : -1;  //only if the rounded value is odd and the next rounded decimal would be 5: alter the outcome to the nearest even number
    return r / f;
}

for(let d of [50 * 2.3659, 2.155,2.145, -2.155, 2.144444, 2.1, 2.5])
    console.log(d, ' -> ', roundMidPointToEven(d, 2)); //test values correspond with outcome of rounding decimals in C#




答案 1 :(得分:0)

您可以按如下方式尝试parseFloat和toFixed函数:

   var mulVal = parseFloat(50) * parseFloat(2.3659);
   var ans = mulVal.toFixed(2);
   console.log(ans);

答案 2 :(得分:0)

Javascript算术并不总是准确的,这种错误的答案并不罕见。我建议您在此方案中使用Math.Round()var.toFixed(1)

使用Math.Round:

var value = parseFloat(50) * parseFloat(2.3659);
var rounded = Math.round(value);
console.log(rounded);

118打印到控制台。

使用toFixed()方法:

var value = parseFloat(50) * parseFloat(2.3659);
var rounded = value.toFixed(1);
console.log(rounded);

118.3打印到控制台。

请注意,使用toFixed(2)会将值设为118.29

希望这有帮助!