Jeroen Jeroen - 5 months ago 16
JSON Question

Format double with at least one decimal in printf

To format a double for JSON with maximal precision but no trailing zero's we use

%.15g
. However in order to distinguish between integers and real numbers we want to format doubles with at least one digit, i.e.
"%.1f"
, except for numbers in scientific notation (which are doubles by definition).

Is there a way to implement this in a single snprint
format
?

double val;
char buf[32];

if(fabs(val) < 1e15 && !fmod(val, 1)){
// whole numbers get at least one decimal
snprintf(buf, 32, "%.1f", val);
} else {
// automatically detemines decimal or scientific notation
snprintf(buf, 32, "%.15g", val);
}

Answer

Just use conversion specifier g, and add .0 at the end of string, if string contains only sign and digit characters. The yajl library has an example implementation:

char buf[32];
sprintf(buf, "%.20g", val);
if (strspn(buf, "0123456789-") == strlen(buf)) {
  strcat(buf, ".0");
}
Comments