/* Render the number nicely from the given item into a string. */ static cJSON_bool print_number(const cJSON * const item, printbuffer * const output_buffer) { unsignedchar *output_pointer = NULL; double d = item->valuedouble; int length = 0; size_t i = 0; unsignedchar number_buffer[26] = {0}; /* temporary buffer to print the number into */ unsignedchar decimal_point = get_decimal_point(); double test = 0.0;
if (output_buffer == NULL) { returnfalse; }
/* This checks for NaN and Infinity */ if (isnan(d) || isinf(d)) { length = sprintf((char*)number_buffer, "null"); } else { /* Try 15 decimal places of precision to avoid nonsignificant nonzero digits */ // 更改这里的1.4,这里指的是保留4位小数 length = sprintf((char*)number_buffer, "%1.4g", d);
/* Check whether the original double can be recovered */ if ((sscanf((char*)number_buffer, "%lg", &test) != 1) || !compare_double((double)test, d)) { /* If not, print with 17 decimal places of precision */ // 更改这里的1.4,这里指的是保留4位小数 length = sprintf((char*)number_buffer, "%1.4g", d); } }
/* reserve appropriate space in the output */ output_pointer = ensure(output_buffer, (size_t)length + sizeof("")); if (output_pointer == NULL) { returnfalse; }
/* copy the printed number to the output and replace locale * dependent decimal point with '.' */ for (i = 0; i < ((size_t)length); i++) { if (number_buffer[i] == decimal_point) { output_pointer[i] = '.'; continue; }