WCF and DataContract : Decimal giving 4 digits after the "." and sometimes only 2 digits

StackOverflow https://stackoverflow.com/questions/22856339

  •  27-06-2023
  •  | 
  •  

Question

I actually have a kind of question that might look crazy, but in WCF I have a simple contract and sometimes when I have the DataContract on a decimal, the service send back 4 digits after the ".". I actually look forward to have only 2 digits. Is it something possible?

By example:

namespace MyContract.Data
{
    [DataContract]
    public class ClassB : ClassA
    {
        [DataMember]
        public decimal VarA { get; set; }

        [DataMember]
        public decimal VarB { get; set; }
    }
}

After the call to the service the output I receive is something like that:

<a:ClassB>
  <a:VarA>47.34</a:VarA>
  <a:VarB>23.1200</a:VarB>
</a:ClassB>

And does anyone know why this happen ?

Was it helpful?

Solution

It happens because DataContractSerializer will simply serialize your decimals 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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top