cJSON icon indicating copy to clipboard operation
cJSON copied to clipboard

cJSON_CreateFloatArray output error

Open Eaglewzw opened this issue 5 years ago • 2 comments

hey,Dav,i got a trouble in this program here i want to store the values of AF array in cJSON but when i used cJSON_CreateFloatArray(aF, 2) the output result is not the original data(0.01 0.15) how should i solve it?

#include <stdio.h> #include "cJSON.h"

#include <stdio.h> #include "cJSON.h"

int main(void) { cJSON *iRoot = NULL; float aF[2] = {0.01, 0.15}; iRoot = cJSON_CreateObject(); cJSON_AddItemToObject(iRoot, "aF", cJSON_CreateFloatArray(aF, 2)); printf("%s \n", cJSON_Print(iRoot)); cJSON_Delete(iRoot); } #include <stdio.h> #include "cJSON.h"

Output: { "aF": [0.00999999977648258, 0.15000000596046448] }

Eaglewzw avatar Dec 16 '20 15:12 Eaglewzw

It is related with #153, which only print significant digits of doubles. Truncating meaningless digits saves space, but causes precise distortion, so I think it needs to be optimized more.

Alanscut avatar Dec 17 '20 08:12 Alanscut

Regarding this, I may have some insight:

On embedded platforms, If a double literal is sent like 1.234, serialized JSON ends up something like either 1.2349999988 or 1.234000002 (not actual number of digits).

If string format "%1.15" at this file is changed to "%.15g", the serialized value from a literal ends up being correct (1.234).

I'm not an expert on this, but perhaps this format %A.BBg is not treated correctly in many compilers. If we were to change it to %.BBg, I wonder if this issue would be corrected. I am not sure about the significance of the "1" before the decimal and if my suggestion is even correct in the context, but it seems to work.

I am also not familiar with what implications actual double precision of the processor hardware has on this.

nik-markovic avatar Jul 27 '21 17:07 nik-markovic