简体   繁体   English

C#XML序列化和十进制值

[英]C# XML Serialization and Decimal Value

I am using XmlSerializer to serialize a C# object that contains a decimal to a string of xml 我正在使用XmlSerializer将包含小数的C#对象序列化为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 我发现精度尤其在变化,即使我显式舍入为以下值,一些值在点之后也得到四个值的输出,例如12564.39得到的输出为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? 您可以实现IXmlSerializable来重新定义序列化对象的方式吗?

Documentation here and a good breakdown of how to implment it here . 文档在这里以及如何implment一个好击穿这里

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? 有关该主题的更多信息,类似的问题: 您可以为日期时间的XmlSerialization指定格式吗?

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. 就我而言,我将其转换为货币,但是您可以使用price.ToString(“ 0.00”)将XML元素转换为带有2个零的十进制。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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