cpprestsdk icon indicating copy to clipboard operation
cpprestsdk copied to clipboard

Add double serialization format

Open harsszegi opened this issue 7 years ago • 3 comments

Hello, is it possible to add a web::json function which would control how doubles in _Number are converted to string? E.g. instead of using the biggest possible precision (std::numeric_limits::digits10 + "%.*g") just use the shortest possible format ("%g").

The reason is that because of the IEEE 754 rounding issues double like 2142.86 is converted as 2142.8600000000001

harsszegi avatar Feb 27 '18 07:02 harsszegi

The code is actually using digits10 + 2. I suspect the reason for this is to guarantee roundtrip value -> string -> value. As you point out this results in some annoying changes when doing string -> value -> string.

There's discussion of the same issue for another JSON implementation at https://github.com/nlohmann/json/issues/360.

garethsb avatar Feb 28 '18 04:02 garethsb

Drive-by comment here. I have no idea what this repo is about, but...

@garethsb wrote:

The code is actually using digits10 + 2. I suspect the reason for this is to guarantee roundtrip value -> string -> value. As you point out this results in some annoying changes when doing string -> value -> string.

digits10 + 2 is an alarming expression. If the intent is indeed to guarantee non-lossy roundtrip value->string->value (a worthy goal), then std::numeric_limits<T>::digits10()+2 happens to produce the correct answer (17) for T=double, by luck, but it produces the wrong answer (8, whereas the correct answer is 9) for T=float.

In general, std::numeric_limits<T>::max_digits10() gives the right answer.

donhatch avatar Feb 04 '22 11:02 donhatch

Thanks, @donhatch. Not that it's any excuse but I suspect the code here and across other codebases that does digits10 + 2 predates C++11. In any case an algorithm that printed the smallest number of digits to round-trip would be even nicer, e.g. the Grisu2 algorithm from Florian Loitsch.

garethsb avatar Feb 04 '22 12:02 garethsb