What is the C printf format directive to output a double as a valid JSON number?

Viewed 286

I'm writing C code that outputs a double into a string to be part of a JSON string.

What C print format directive should I use to output the double?

As far as I know, a valid JSON number must never start with '.'. It must start with "0." Instead. The exponent and fractional part are not output when all 0.

The printed number must have the maximum precision, but also do smart rounding so that the double 0.3 is printed as 0.3. This is tricky to handle when the input number is 0.3 for instance.

1 Answers

You should probably use the %g format specifier:

#include <math.h>
#include <stdio.h>

int main(void)
{
    printf("%.15g\n", 0.3);
    printf("%.15g\n", M_PI);
    printf("%.15g\n", 0.3 * 1.0E+6);
    printf("%.15g\n", 0.3 * 1.0E-6);
    printf("%.15g\n", M_PI * 1.0E-12);
    printf("%.15g\n", M_PI * 1.0E+12);

    printf("%g\n", 0.3);
    printf("%g\n", M_PI);
    printf("%g\n", 0.3 * 1.0E+6);
    printf("%g\n", 0.3 * 1.0E-6);
    printf("%g\n", M_PI * 1.0E-12);
    printf("%g\n", M_PI * 1.0E+12);
    return 0;
}

Output:

0.3
3.14159265358979
300000
3e-07
3.14159265358979e-12
3141592653589.79
0.3
3.14159
300000
3e-07
3.14159e-12
3.14159e+12

Do not include the + modifier in the format specifier; leading + signs are not valid in a JSON number.

The plain %g format specifier only produces up to 6 digits. If you don't wish to lose precision, you need to specify more than 6 using a notation such as %.15g. You can get into detailed arguments about whether 15, 16, or 17 is the best choice to make to avoid losing precision — it depends on the context. Nevertheless, 15 is often a good number to use.

Related