RSS

Banker’s rounding in .NET

23 Feb

Here is a table to help clarify common rounding methods, including round half away from zero and round half to even, also known as Gaussian rounding or Banker’s rounding:

Numbers Round half away from zero Banker’s rounding
-1.9 -2 -2
-1.6 -2 -2
-1.5 -2 -2
-1.4 -1 -1
-1.1 -1 -1
-0.9 -1 -1
-0.6 -1 -1
-0.5 -1 0
-0.4 0 0
-0.1 0 0
0.1 0 0
0.4 0 0
0.5 1 0
0.6 1 1
0.9 1 1
1.1 1 1
1.4 1 1
1.5 2 2
1.6 2 2
1.9 2 2


.NET Math.Round() uses Banker’s rounding as default which follows the IEEE 754 standard. We can choose rounding method by specifying the MidpointRounding parameter. The rounding results above are calculated by the C# code below.



for (double number = -20; number {
    TableRow tr = new TableRow();
    TableCell[] cells = new TableCell[3];
    for (int i = 0; i < cells.Length; i++ )
    {
        cells[i] = new TableCell();
    }
    cells[0].Text = (number/10).ToString();
    cells[1].Text = Math.Round((number / 10), MidpointRounding.AwayFromZero).ToString();
    cells[2].Text = Math.Round((number / 10)).ToString();
    tr.Cells.AddRange(cells);
    this.RoundingTable.Rows.Add(tr);
}
Advertisements
 
Leave a comment

Posted by on February 23, 2012 in .NET, C#

 

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

 
%d bloggers like this: