Javascript and C# rounding hell

2019-06-06 05:07发布

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?

2条回答
\"骚年 ilove
2楼-- · 2019-06-06 05:43

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. E.g. 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
查看更多
做个烂人
3楼-- · 2019-06-06 06:03

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.

查看更多
登录 后发表回答