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
G17format specifier, as documented here:or
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.Parseon the string, you will get back the exact same value: