简体   繁体   中英

Javascript and C# rounding hell

As you know due to genius rounding rule in C# we are getting 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 client side in Javascript I am getting:

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 validations in the backend that is failing due to this. What is the correct way to deal with this kind of situation? How can I sync C# and Javascript rounding to be sure they both round to the same values?

There´s an overload in C#´s Math.Round accepting an indicator to detmerine how to round when number is half-way between two others. Eg MidPointToEven rounds the 0.5 to zero as zero is the neartest 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

As per defualt MidPointToEven is used your number will allways be rounded to the nearest even number. Thuis you get those results:

2.155 --> 2.16
2.145 --> 2.14

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

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

The default value for decimals is MidpointRounding.ToEven AKA banker's rounding , it's designed to minimize the bias over multiple rounding operations.

The round half to even method treats positive and negative values symmetrically, and is therefore free of sign bias. More importantly, for reasonable distributions of y values, the average value of the rounded numbers is the same as that of the original numbers . However, this rule will introduce a towards-zero bias when y − 0.5 is even, and a towards-infinity bias for when it is odd. Further, it distorts the distribution by increasing the probability of evens relative to odds.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM