Jeroen Jeroen - 1 year ago 59
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

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

Is there a way to implement this in a single snprint

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 Source

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");