.comment-link {margin-left:.6em;}
Gert .Net
[GertDotNet]
20080321
 
string.Format != Math.Round
Numbers with string.Format are rounded differently when using Math.Round using the same number of digits.

You can see this when running the following code:
            for (int i = 0; i < 10; i++)
{
decimal d = 1m + (decimal)i / 100m;
System.Diagnostics.Debug.WriteLine(string.Format("Format only: {0:f1} - Rounded: {1:f1} - raw: {0}",
d, Math.Round(d, 1)));
}


This gives the following output:
Format only: 1,0 - Rounded: 1,0 - raw: 1
Format only: 1,0 - Rounded: 1,0 - raw: 1,01
Format only: 1,0 - Rounded: 1,0 - raw: 1,02
Format only: 1,0 - Rounded: 1,0 - raw: 1,03
Format only: 1,0 - Rounded: 1,0 - raw: 1,04
Format only: 1,1 - Rounded: 1,0 - raw: 1,05
Format only: 1,1 - Rounded: 1,1 - raw: 1,06
Format only: 1,1 - Rounded: 1,1 - raw: 1,07
Format only: 1,1 - Rounded: 1,1 - raw: 1,08
Format only: 1,1 - Rounded: 1,1 - raw: 1,09

Take a special look at the line with 1,05 in the raw column. There is a difference between the passing the raw and the rounded value into the string.Format method.

If you look at the documentation of the Math.Round method:

The behavior of this method follows IEEE Standard 754, section 4. This kind of rounding is sometimes called rounding to nearest, or banker's rounding. It minimizes rounding errors that result from consistently rounding a midpoint value in a single direction.


You can control the behaviour of this rounding using an overloaded method with the MidPointRounding parameters specified. Looks like the default for string.Format is AwayFromZero, while Math.Round uses ToEven as a default.

Powered by Blogger