XMLSerializer, customize float serialization

  • Thread starter Thread starter Abra
  • Start date Start date
A

Abra

Hello,
I am using the XmlSerializer clas to serialize/deserialize XML files.
I have a XML file containing elements which have attributes of type
float. If the value of the float attribute in my application is for
example 43.5678, after the serialization I get the value
"43.5677999999999". Is it any way to control the formatting of the float
type, to limit for example the number of positions after the comma ?
The only solution that I found is to change the attribute type from
float to string, and format the string programmatically by myself ... Is
there any better solution available ? I did not found any method to
overload the "ToString()" method for the floats ... And also the
XmlWriterSettings class does not offer any interface to control the
float format ...
Thanks in advance for your help.
Regards,
Abra
 
Abra,

The string method isn't a bad solution. Just make sure you either
TryParse (preferrable) or catch NumberFormatException (less preferred)
on deserialization.

Part of the problem is that you don't really want a float. The datum
you're trying to convey in your example is better cast into a decimal
type than a float type. If you were using decimal, you wouldn't have
this problem.


Stephan
 
Back
Top