MCPcopy Create free account
hub / github.com/TheForceEngine/TheForceEngine / print_number

Function print_number

TheForceEngine/TFE_System/cJSON.c:550–617  ·  view source on GitHub ↗

Render the number nicely from the given item into a string. */

Source from the content-addressed store, hash-verified

548
549/* Render the number nicely from the given item into a string. */
550static cJSON_bool print_number(const cJSON * const item, printbuffer * const output_buffer)
551{
552 unsigned char *output_pointer = NULL;
553 double d = item->valuedouble;
554 int length = 0;
555 size_t i = 0;
556 unsigned char number_buffer[26] = {0}; /* temporary buffer to print the number into */
557 unsigned char decimal_point = get_decimal_point();
558 double test = 0.0;
559
560 if (output_buffer == NULL)
561 {
562 return false;
563 }
564
565 /* This checks for NaN and Infinity */
566 if (isnan(d) || isinf(d))
567 {
568 length = sprintf((char*)number_buffer, "null");
569 }
570 else if(d == (double)item->valueint)
571 {
572 length = sprintf((char*)number_buffer, "%d", item->valueint);
573 }
574 else
575 {
576 /* Try 15 decimal places of precision to avoid nonsignificant nonzero digits */
577 length = sprintf((char*)number_buffer, "%1.15g", d);
578
579 /* Check whether the original double can be recovered */
580 if ((sscanf((char*)number_buffer, "%lg", &test) != 1) || !compare_double((double)test, d))
581 {
582 /* If not, print with 17 decimal places of precision */
583 length = sprintf((char*)number_buffer, "%1.17g", d);
584 }
585 }
586
587 /* sprintf failed or buffer overrun occurred */
588 if ((length < 0) || (length > (int)(sizeof(number_buffer) - 1)))
589 {
590 return false;
591 }
592
593 /* reserve appropriate space in the output */
594 output_pointer = ensure(output_buffer, (size_t)length + sizeof(""));
595 if (output_pointer == NULL)
596 {
597 return false;
598 }
599
600 /* copy the printed number to the output and replace locale
601 * dependent decimal point with '.' */
602 for (i = 0; i < ((size_t)length); i++)
603 {
604 if (number_buffer[i] == decimal_point)
605 {
606 output_pointer[i] = '.';
607 continue;

Callers 1

print_valueFunction · 0.85

Calls 3

get_decimal_pointFunction · 0.85
compare_doubleFunction · 0.85
ensureFunction · 0.85

Tested by

no test coverage detected