C# XML Serialization and Decimal Value
Solution 1
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?
Solution 2
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.
Solution 3
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.
Patrick
Updated on June 04, 2022Comments
-
Patrick almost 2 years
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
-
Louis Somers over 7 yearsAdding the
DataType="decimal"
argument gave me a Runtime InvalidOperationException with the message "decimal is an invalid value for the property XmlElementAttribute.DataType. decimal cannot be converted to System.String." (note the message was localized and I translated it back to English so it could differ a little).