AJM
AJM

Reputation: 32490

C# XML Serialization and Decimal Value

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

Upvotes: 3

Views: 24316

Answers (3)

Auguste
Auguste

Reputation: 2201

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.

Upvotes: 4

Jon
Jon

Reputation: 3213

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.

Upvotes: 3

Matzi
Matzi

Reputation: 13925

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?

Upvotes: 2

Related Questions