It happens because DataContractSerializer
will simply serialize your decimal
s as they themselves want to be represented. You will get the same output if you do Console.Write
or anything else without specifying some format.
The reason is that there is (could be) a difference between 23.12 and 23.1200, namely precision. Let's imagine that the values represent some measurement you are doing in a lab. The extra zeroes at the end imply that you have measured the value precisely enough that you know that it is not 23.1204, or 23.1211. But 23.12 on the other hand has a lower precision, and could be the result of the same measurement, but with an impreciser instrument.
Now, this may not be relevant in your specific usecase. If you have a need to return exactly x
digits, you can round your decimals before serialization:
ClassB b = // some initialization
b.VarA = Decimal.Round(b.VarA, x);
b.VarB = Decimal.Round(b.VarB, x);
This throws away some data, though, so be careful if the precision is actually meaningful (as noted above).
If this is merely for presentation purposes, consider doing the formatting in the display instead.