Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to serialize a double

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#?

like image 512
tenfour Avatar asked Dec 15 '22 22:12

tenfour


2 Answers

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")
like image 116
porges Avatar answered Jan 01 '23 00:01

porges


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.

like image 40
saille Avatar answered Dec 31 '22 22:12

saille