1

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.

chmike
  • 20,922
  • 21
  • 83
  • 106

1 Answers1

3

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.

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
  • Is 15 enough ? I just tested it with the Go language, and the bare %g is indeed fine. Not sure if the ".15" is required. – chmike Nov 27 '20 at 13:33
  • See the extended example. Anything much more and the code needs to be restructured to permit a loop of possible format strings and another loop over a range of possible numbers. However, that's a basic refactoring exercise. – Jonathan Leffler Nov 27 '20 at 13:38
  • 1
    Found [here](https://stackoverflow.com/a/54162486/75517) why the precision should be set to 15 and not beyond. – chmike Nov 27 '20 at 13:58