简体   繁体   中英

C# XML Serialization and Decimal Value

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

eg

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 eg 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

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.

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM