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.