Render the number nicely from the given item into a string. */
| 400 | |
| 401 | /* Render the number nicely from the given item into a string. */ |
| 402 | static unsigned char *print_number(const cJSON *item, printbuffer *p) |
| 403 | { |
| 404 | unsigned char *str = NULL; |
| 405 | double d = item->valuedouble; |
| 406 | /* special case for 0. */ |
| 407 | if (d == 0) |
| 408 | { |
| 409 | if (p) |
| 410 | { |
| 411 | str = ensure(p, 2); |
| 412 | } |
| 413 | else |
| 414 | { |
| 415 | str = (unsigned char*)cJSON_malloc(2); |
| 416 | } |
| 417 | if (str) |
| 418 | { |
| 419 | strcpy((char*)str,"0"); |
| 420 | } |
| 421 | } |
| 422 | /* value is an int */ |
| 423 | else if ((FABS(((double)item->valueint) - d) <= DBL_EPSILON) && (d <= INT_MAX) && (d >= INT_MIN)) |
| 424 | { |
| 425 | if (p) |
| 426 | { |
| 427 | str = ensure(p, 21); |
| 428 | } |
| 429 | else |
| 430 | { |
| 431 | /* 2^64+1 can be represented in 21 chars. */ |
| 432 | str = (unsigned char*)cJSON_malloc(21); |
| 433 | } |
| 434 | if (str) |
| 435 | { |
| 436 | sprintf((char*)str, "%d", item->valueint); |
| 437 | } |
| 438 | } |
| 439 | /* value is a floating point number */ |
| 440 | else |
| 441 | { |
| 442 | if (p) |
| 443 | { |
| 444 | /* This is a nice tradeoff. */ |
| 445 | str = ensure(p, 64); |
| 446 | } |
| 447 | else |
| 448 | { |
| 449 | /* This is a nice tradeoff. */ |
| 450 | str = (unsigned char*)cJSON_malloc(64); |
| 451 | } |
| 452 | if (str) |
| 453 | { |
| 454 | /* This checks for NaN and Infinity */ |
| 455 | if ((d * 0) != 0) |
| 456 | { |
| 457 | sprintf((char*)str, "null"); |
| 458 | } |
| 459 | else if ((FABS(FLOOR(d) - d) <= DBL_EPSILON) && (FABS(d) < 1.0e60)) |