C#XML序列化和十进制值 [英] C# XML Serialization and Decimal Value
问题描述
我正在使用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序列化和十进制值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!