C# XML Serialization and Decimal Value

风格不统一 提交于 2019-12-24 02:09:07

问题


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


回答1:


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.




回答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?




回答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.



来源:https://stackoverflow.com/questions/10330155/c-sharp-xml-serialization-and-decimal-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!