我正在使用XmlSerializer将包含小数的C#对象序列化为xml字符串
I am using XmlSerializer to serialize a C# object that contains a decimal to a string of xml
例如
AnObject.ADecimalValue我发现精度特别是变化的,即使我显式舍入为以下值,例如某些值在点之后输出具有四个值的输出.12564.39输出为12564.3900
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);
下面是序列化代码.
XmlSerializer serializer = new XmlSerializer(typeof(AnObject)); using (StringWriter writer = new StringWriter()) { serializer.Serialize(writer, source); string result = writer.ToString(); return result; }如何确保小数点后仅输出两个值
推荐答案您可以实现 IXmlSerializable 来重新定义序列化对象的方式吗?
Could you implement IXmlSerializable to redefine how you serialise your object?
文档此处,此处.
然后有一个帖子此处是与您的问题相似(但无关)的人.您可以正确地将小数点四舍五入,然后查看是否可行,否则可以将其写为字符串.
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.
更多推荐
C#XML序列化和十进制值
发布评论