Tencent / rapidjson

A fast JSON parser/generator for C++ with both SAX/DOM style API
http://rapidjson.org/
Other
14.28k stars 3.53k forks source link

Float formatting when writting output #1752

Open NadegeEv opened 4 years ago

NadegeEv commented 4 years ago

Hello,

I'm trying to save some float values into an Array in a Document and then to save it into a json file. I need a precision of 12 so I used writer.SetMaxDecimalPlaces(12); It works in most cases but if there are 6 zeros or more, the writer uses the exponential notation, which I don't want at all.

just a little example: `float value = 0.000000134110; // 6 zeros : exponential float value2 = 0.00000134110; // 5 zeros ok float value3 = 0.0134110; // ok float value4 = 0.013411025745467674374; // too long : truncate ok

Document doc(kArrayType); doc.PushBack(Value(value).Move(), doc.GetAllocator()); doc.PushBack(Value(value2).Move(), doc.GetAllocator()); doc.PushBack(Value(value3).Move(), doc.GetAllocator()); doc.PushBack(Value(value4).Move(), doc.GetAllocator());

// write into a file StringBuffer buffer; Writer writer(buffer); writer.SetMaxDecimalPlaces(12); // to have the good precision doc.Accept(writer); const char output = buffer.GetString(); FILE out; out = fopen("essai.json", "w"); if (out != NULL){ fprintf(out, "%s", output); fclose(out); `

the final essai.json is the following: [1.3410999599727803e-7,0.000001341099,0.01341100037,0.013411025516]

Has anyone an idea to avoid the exponential notation ?

Thanks

miloyip commented 4 years ago

It seems to be a bug. Do you want to try to fix it and submit a PR?

NadegeEv commented 4 years ago

Hello, I found the line and so the interest: in internal/dtoa.h, in Prettify, we consider that if there is 6 zeros or more (0.00000042), it is better to write the exponential form. It is I think not a "bug" For others who wants to keep the notation without exponential even in this case, you should replace in internal/dtoa.h, Prettify, line 176: else if (-6 < kk && kk <= 0) { => else if (-maxDecimalPlaces < kk && kk <= 0) {

wusikijeronii commented 1 year ago

Today I tried this beautiful project for the first time, and I faced a similar issue. I wanna store numbers in exponential notation. For example, I used 1024e+1, but even using this small number, I get the error:

Assertion failed: data_.f.flags & kIntFlag, file C:/Users/alekesej/Documents/Programming/GifMaker-Vk/src/3rd-party/rapidjson/include/rapidjson\document.h, line 1817

I also read about the JSON specification and that numbers in exponential notation are supported in the JSON format.