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. E.g. MidPointToEven rounds the 0.5 to zero as zero is the neartest even number:
As per defualt
MidPointToEven
is used your number will allways be rounded to the nearest even number. Thuis you get those results:You can specify the midpoint rounding rule to be used in C#:
The default value for decimals is
MidpointRounding.ToEven
AKA banker's rounding, it's designed to minimize the bias over multiple rounding operations.