最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Javascript and C# rounding hell - Stack Overflow

programmeradmin4浏览0评论

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?

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?

Share Improve this question asked Jun 23, 2017 at 8:13 Giorgi NakeuriGiorgi Nakeuri 35.8k8 gold badges49 silver badges78 bronze badges 0
Add a ment  | 

2 Answers 2

Reset to default 6

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

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.

发布评论

评论列表(0)

  1. 暂无评论