Render the number nicely from the given item into a string. */
| 594 | |
| 595 | /* Render the number nicely from the given item into a string. */ |
| 596 | static cJSON_bool print_number(const cJSON * const item, printbuffer * const output_buffer) |
| 597 | { |
| 598 | unsigned char *output_pointer = NULL; |
| 599 | double d = item->valuedouble; |
| 600 | int length = 0; |
| 601 | size_t i = 0; |
| 602 | unsigned char number_buffer[26] = {0}; /* temporary buffer to print the number into */ |
| 603 | unsigned char decimal_point = get_decimal_point(); |
| 604 | double test = 0.0; |
| 605 | |
| 606 | if (output_buffer == NULL) |
| 607 | { |
| 608 | return false; |
| 609 | } |
| 610 | |
| 611 | /* This checks for NaN and Infinity */ |
| 612 | if (isnan(d) || isinf(d)) |
| 613 | { |
| 614 | length = sprintf((char*)number_buffer, "null"); |
| 615 | } |
| 616 | else if(d == (double)item->valueint) |
| 617 | { |
| 618 | length = sprintf((char*)number_buffer, "%d", item->valueint); |
| 619 | } |
| 620 | else |
| 621 | { |
| 622 | /* Try 15 decimal places of precision to avoid nonsignificant nonzero digits */ |
| 623 | length = sprintf((char*)number_buffer, "%1.15g", d); |
| 624 | |
| 625 | /* Check whether the original double can be recovered */ |
| 626 | if ((sscanf((char*)number_buffer, "%lg", &test) != 1) || !compare_double((double)test, d)) |
| 627 | { |
| 628 | /* If not, print with 17 decimal places of precision */ |
| 629 | length = sprintf((char*)number_buffer, "%1.17g", d); |
| 630 | } |
| 631 | } |
| 632 | |
| 633 | /* sprintf failed or buffer overrun occurred */ |
| 634 | if ((length < 0) || (length > (int)(sizeof(number_buffer) - 1))) |
| 635 | { |
| 636 | return false; |
| 637 | } |
| 638 | |
| 639 | /* reserve appropriate space in the output */ |
| 640 | output_pointer = ensure(output_buffer, (size_t)length + sizeof("")); |
| 641 | if (output_pointer == NULL) |
| 642 | { |
| 643 | return false; |
| 644 | } |
| 645 | |
| 646 | /* copy the printed number to the output and replace locale |
| 647 | * dependent decimal point with '.' */ |
| 648 | for (i = 0; i < ((size_t)length); i++) |
| 649 | { |
| 650 | if (number_buffer[i] == decimal_point) |
| 651 | { |
| 652 | output_pointer[i] = '.'; |
| 653 | continue; |
no test coverage detected