Changes to Decimal.ToString between V1.0 and V1.1

[Anthony Moore]

There was a change to Decimal class in V1.1 to preserve trailing zeros in the default foramtting. I thought this was well known, but we just recently got a customer support issue on it. Here is an entry that we will shortly add to the numerics FAQ.

Why did Decimal.ToString change between V1.0 and V1.1 and how do I work around it?

In general there were very few breaking changes between V1.0 and V1.1. One of the more noticeable ones was that Decimal.ToString changed to preserve trailing zeros and the default ToString displays them.

 

Decimal value = 12.246000m;

Console.WriteLine(value.ToString());

 

In V1.0 this printed “12.246”. In V1.1 this prints “12.246000”. This was an intentional change in order to adhere to the ECMA CLI standard.

 

Note that this change only affects formatting. The values “12.246” and “12.246000” are still considered to be the same value if you compare them or do arithmetic on them. The trailing zeros, or scale, of the decimal is peripheral information that is preserved across most operations, but is not significant to the equality of the value. As such, this should only break code that depends on the specific string format.

 

To work around this and go back to the V1.0 behavior, use the “G29” format:

 

Decimal value = 12.246000m;

Console.WriteLine(value.ToString(“G29”));

 

This will print “12.246” in either version 1.0 or version 1.1. The “G” format with a number means to format that many significant digits. Because 29 is the most significant digits that a Decimal can have, this will effectively truncate the trailing zeros without rounding.