The woes of Silverlight binding to a decimal type.

I came across something that grabbed my attention the other day.  I was working with a Silverlight application and had bound TextBox controls to two separate decimal properties of a ViewModel class.  I was using the default formatting for display and was quite perplexed when I found that even though both properties had the same value, i.e. 100, one TextBox displayed 100.00 and the other 100.0000.  After doing a little digging I found that the root cause of this behavior is that decimal types in .NET carry not only a value but that value's precision as well (apparently since .NET 1.1).  To see this in action take this case:

decimal d1 = 100;  
decimal d2 = 100.00M;  
Console.WriteLine("d1: {0}, d2: {1}, Equal={2}", d1, d2, d1 == d2);  

The result will be the output "d1: 100, d2: 100.00, Equal=true" which is to say that the two variables have equal values but different precisions and thus the ToString method on each yields a different result.

In my particular case one value was being set directly from a database field who's precision was defined as two decimal places.  The second property, however, was undergoing a calculation.  For the particular case with which I made this discovery a database field defined with a precision of two decimal places was being multiplied by another decimal value with a precision of two decimal places.  Mathematically, performing such an operation should indeed yield a decimal value with a precision of four decimal places.  However, this can be something of a problem if you have properties data bound to controls with default formatting because ToString (default format) will display the full precision of the decimal value and that precision is set automatically by the mathematical operations performed in setting the property value.

I've come to the conclusion that it's a best practice to explicitly specify formats for all data bound floating point properties unless you don't care about a consistent display for such properties.  Unless you specify formats for these properties or know with 100% certainty how such property values are being calculated and assigned you will be guaranteed inconsistent display results.