2

I am using XmlSerializer to serialize a C# object that contains a decimal to a string of xml

e.g.

AnObject.ADecimalValue

I am finding the precision is varying in particular even if I explicitly round as below some values are getting output with four values after the point e.g. 12564.39 gets output as 12564.3900

AnObject.ADecimalValue = decimal.Round(AnObject.ADecimalValue, 2);

The serializing code is below.

   XmlSerializer serializer = new XmlSerializer(typeof(AnObject));

    using (StringWriter writer = new StringWriter())
    {
        serializer.Serialize(writer, source);

        string result = writer.ToString();

        return result;
    }

How can I ensure only two values are output out after the decimal point

AJM
  • 32,054
  • 48
  • 155
  • 243

3 Answers3

3

Could you implement IXmlSerializable to redefine how you serialise your object?

Documentation here and a good breakdown of how to implment it here.

Then there's a post here by someone with a similar (but not related) issue to yours. You could round your decimal correctly and see if that works, if not then you can write it out as a string.

Community
  • 1
  • 1
Jon
  • 3,173
  • 3
  • 39
  • 66
3

Here's how I resolved a similar problem and it's working perfectly for me.

    private decimal  price;

    [XmlElement(DataType="decimal")]
    public string  Price
    {
        get { return price.ToString("c"); }
        set { price = Convert.ToDecimal(value); }
    }

In my case, I converted it to currency, but you can use price.ToString("0.00") to convert the XML element to decimal with 2 zeros.

Auguste
  • 2,007
  • 2
  • 17
  • 25
  • Adding the `DataType="decimal"` argument gave me a Runtime InvalidOperationException with the message "decimal is an invalid value for the property XmlElementAttribute.DataType. decimal cannot be converted to System.String." (note the message was localized and I translated it back to English so it could differ a little). – Louis Somers Sep 22 '16 at 08:41
2

I don't think that rounding a floating point number can help this. The serializer converts the number to string according to it's own rules. The best you can do is to introduce a new string property, and format the number in that and serialize it instead of the original number.

More on the topic, similar issue: Can you specify format for XmlSerialization of a datetime?

Community
  • 1
  • 1
Matzi
  • 13,770
  • 4
  • 33
  • 50