I am serializing values to an XML document. When I serialize a double
, I want to make sure I am not losing any precision, and that culture will not interfere. Or any other "gotchas" that I haven't thought of.
Similarly for DateTime
, I use ToBinary()
to get a value that's very safe to serialize.
So, what is the best method to serialize / deserialize a double
value in C#?
In order to parse back the exact value, you should use the G17
format specifier, as documented here:
d.ToString("G17")
or
$"{d:G17}"
Note that this can fail to roundtrip on versions below .NET Core 3.0.
Original answer below; the "r"
format specifier mentioned actually has a bug so the documentation was incorrect.
The round-trip format specifier "r" guarantees that if you use double.Parse
on the string, you will get back the exact same value:
d.ToString("r")
Checkout XmlConvert.ToString(double value)
This handles infinity too:
If value is Double.PositiveInfinity or Double.NegativeInfinity, this method returns the string INF or -INF respectively.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With