Is there a best practice for using .Net rounding algorithm for decimal rounding operations that takes into account internal systems? Real world experience appreciated.
.Net uses Bankers rounding by default. ( MidpointRounding.ToEven ). This contradicts the original SQL Server database that I use, since SQL Server uses arithmetic rounding ( MidpointRounding.AwayFromZero ) and does not have a built-in function to simulate Banker rounding.
Note. I use decimal code (18, 4) in SQL Server, decimal in .Net
Example .Net example by default Banker rounding with two decimal places versus rounding SQL Server to two decimal places:
| Value | .Net | SQL Server |
|
| 2.445 | 2.44 | 2.45 |
| 2.455 | 2.46 | 2.46 |
| 2.465 | 2.46 | 2.47 |
| 3.445 | 3.44 | 3.45 |
| 3.455 | 3.46 | 3.46 |
| 3.465 | 3.46 | 3.47 |
// t-sql
declare @decimalPlaces int
set @decimalPlaces = 2
select round(convert(decimal(18, 4), 2.445), @decimalPlaces)
select round(convert(decimal(18, 4), 2.455), @decimalPlaces)
select round(convert(decimal(18, 4), 2.465), @decimalPlaces)
select round(convert(decimal(18, 4), 3.445), @decimalPlaces)
select round(convert(decimal(18, 4), 3.455), @decimalPlaces)
select round(convert(decimal(18, 4), 3.465), @decimalPlaces)
// .Net
var algorithm = MidpointRounding.ToEven;
var decimalPlaces = 2;
Console.WriteLine(decimal.Round(2.445M, decimalPlaces, algorithm).ToString()); // 2.44
Console.WriteLine(decimal.Round(2.455M, decimalPlaces, algorithm).ToString()); // 2.46
Console.WriteLine(decimal.Round(2.465M, decimalPlaces, algorithm).ToString()); // 2.46
Console.WriteLine(decimal.Round(3.445M, decimalPlaces, algorithm).ToString()); // 3.44
Console.WriteLine(decimal.Round(3.455M, decimalPlaces, algorithm).ToString()); // 3.46
Console.WriteLine(decimal.Round(3.465M, decimalPlaces, algorithm).ToString()); // 3.46
- SQL Server , , .Net - Banker Rounding.
, .Net, (nopCommerce) Banker , , .
, : (MidpointRounding.AwayFromZero) .Net?