MCPcopy Create free account
hub / github.com/antirez/botlib / print_number

Function print_number

cJSON.c:545–608  ·  view source on GitHub ↗

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

Source from the content-addressed store, hash-verified

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

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