'How to set precision for json_real while doing json_dump using jansson library

If a double value of 8.13 is passed into json_real and dump the json i see that its printing 8.1300000000000008, Is there any way to get 8.13 or 8.13000000000000000 exactly in C?

    double test = 8.13;
    json_t* msgtest = json_object();
    json_object_set_new(msgtest, "test", json_real(test));
    char* msgStr;
    msgStr = json_dumps(msgtest, 0);


Solution 1:[1]

You can use JSON_REAL_PRECISION, introduced in jansson 2.7.

Output all real numbers with at most n digits of precision. The valid range for n is between 0 and 31 (inclusive), and other values result in an undefined behavior.

By default, the precision is 17, to correctly and losslessly encode all IEEE 754 double precision floating point numbers.

Consider the following program:

#include <jansson.h>

int main() {
    double test = 8.13;
    json_t* msgtest = json_object();
    json_object_set_new(msgtest, "test", json_real(test));
    printf("%s\n", json_dumps(msgtest, JSON_REAL_PRECISION(3)));
}

It prints

{"test": 8.13}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 KevinG