Multiplication gives approximate results

Hm. I have a problem with roundings on the client side, which is then checked in the backend, and the check fails due to this problem. Here is the previous Javascript and C # rounding hell question

So what I do:

On the client side:

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 

In backend ( 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 

And the check is not performed. Can I do something on the client side?

+5
source share
3 answers

We did not test this extensively, but the function below should emulate the "MidPointToEven" rounding:

 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# 
0
source

Can you try the parseFloat and toFixed functions as follows:

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

Javascript Arithmetic is not always accurate, and such erroneous answers are not unusual. I would suggest that you use Math.Round() or var.toFixed(1) for this scenario.

Using Math.Round:

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

Prints 118 on the console.

Using the toFixed () method:

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

Prints 118.3 on the console.

Note that using toFixed(2) will give a value as 118.29 .

Hope this helps!

0
source

Source: https://habr.com/ru/post/1269144/


All Articles