C#XML序列化和十进制值

编程入门 行业动态 更新时间:2024-10-27 12:26:31
本文介绍了C#XML序列化和十进制值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在使用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序列化和十进制值

本文发布于:2023-11-08 22:16:32,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1570597.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:序列化   XML   十进制值

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!