json-c: Format new double object type?

622 Views Asked by At

I use the json-c lib to create a json-formated string. I have some float values and json-c does some conversion to double which leads to some errors:

float nachtmodusfaktor;
nachtmodusfaktor = 0.8;

json_object_object_add(jsons[8],"nachtmodusfaktor",json_object_new_double(round(nachtmodusfaktor * 10) / 10));

The result in the json string is:

     "nachtmodusfaktor": 0.80000000000000004,

It does not matter if I do the round() call or not. In both cases there are these glitches.

Is there a way to tell the json-c library to put the object in a defined format just with printf (ie "%5.2f") which then would show 0.80 instead of the above?

Or do you have an idea for a workaround?

Thanks!

/KNEBB

1

There are 1 best solutions below

1
On BEST ANSWER

It's exactly why the function json_object_new_double_s exists:

from doc

Create a new json_object of type json_type_double, using the exact serialized representation of the value.

This allows for numbers that would otherwise get displayed inefficiently (e.g. 12.3 => "12.300000000000001") to be serialized with the more convenient form.

json_object_new_double(round(nachtmodusfaktor * 10) / 10); should be replaced by:

   char buffer[8];
   sprintf(buffer, "%f", nachtmodusfaktor);
   json_object_new_double_s(nachtmodusfaktor, buffer);