Javascript and C # round off hell

As you know, because of the brilliant rounding rule in C# , we get the following values:

 decimal d = 2.155M; var r = Math.Round(d, 2); //2.16 decimal d = 2.145M; var r = Math.Round(d, 2); //2.14 

Now on the client side in Javascript I get:

 2.155.toFixed(2) "2.15" 2.145.toFixed(2) "2.15" kendo.toString(2.155, 'n2') "2.16" kendo.toString(2.145, 'n2') "2.15" 

But I have checks in the backend, which because of this does not work. What is the right way to deal with this situation? How can I synchronize the rounding of C# and Javascript to make sure they are both rounded to the same value?

0
source share
2 answers

There is an overload in C # Math.Round , which takes an indicator to determine how to round when a number is halfway between the other two. For instance. MidPointToEven rounds from 0.5 to zero, since zero is the most odd even number:

 decimal d = 2.155M; var r = Math.Round(d, 2, MidPointRounding.AwayFromZero); //2.16 decimal d = 2.145M; var r = Math.Round(d, 2, MidPointRounding.AwayFromZero); //2.15 

According to defualt MidPointToEven your number will be rounded to the nearest even number. Thuis you will get those results:

 2.155 --> 2.16 2.145 --> 2.14 
+5
source

You can specify the midpoint rounding rule that will be used in C #:

 decimal d = 2.145M; var r = Math.Round(d, 2, MidpointRounding.AwayFromZero); //2.15 

The default value for decimal places is MidpointRounding.ToEven AKA banking rounding , it is designed to minimize bias across multiple rounding operations.

The round and even method accepts positive and negative values โ€‹โ€‹symmetrically and, therefore, is free from sign bias. More importantly, for reasonable distributions of y values, the average of the rounded numbers is the same as the original numbers . However, this rule will lead to a shift to zero when y - 0.5 is even, and a shift to infinity when it is odd. In addition, it distorts the distribution, increasing the probability of occurrence relative to the coefficients.

+5
source

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


All Articles