c# - Rounding to 2 decimal places, without using banker's rounding -
.net , compact framework default use banker's rounding means value: 1,165 rounded to: 1,16.
sql server opposite rounds 1,17 me correct behaviour.
has come across rounding topic , have workaround compact framework? (in .net there additional parameter has influence on rounding behaviour)
here method can use instead of decimal.round:
public static decimal roundhalfup(this decimal d, int decimals) { if (decimals < 0) { throw new argumentexception("the decimals must non-negative", "decimals"); } decimal multiplier = (decimal)math.pow(10, decimals); decimal number = d * multiplier; if (decimal.truncate(number) < number) { number += 0.5m; } return decimal.round(number) / multiplier; }
taken from: why .net use banker's rounding default?
this question asks why .net uses bankers rounding. believe read you.
to answer why
this bankers algorithm means results collected evenly spread of rounding up/down when decimal == .5, out data results.
here's link describes mr. skeet
Comments
Post a Comment