reformatting: print_number

This commit is contained in:
Max Bruckner 2016-09-27 23:47:13 +07:00
parent 282006d918
commit 67845e3dc6
1 changed files with 71 additions and 28 deletions

99
cJSON.c
View File

@ -270,35 +270,78 @@ static int update(printbuffer *p)
} }
/* Render the number nicely from the given item into a string. */ /* Render the number nicely from the given item into a string. */
static char *print_number(cJSON *item,printbuffer *p) static char *print_number(cJSON *item, printbuffer *p)
{ {
char *str=0; char *str = 0;
double d=item->valuedouble; double d = item->valuedouble;
if (d==0) /* special case for 0. */
{ if (d == 0)
if (p) str=ensure(p,2); {
else str=(char*)cJSON_malloc(2); /* special case for 0. */ if (p)
if (str) strcpy(str,"0"); {
} str = ensure(p, 2);
else if (fabs(((double)item->valueint)-d)<=DBL_EPSILON && d<=INT_MAX && d>=INT_MIN) }
{ else
if (p) str=ensure(p,21); {
else str=(char*)cJSON_malloc(21); /* 2^64+1 can be represented in 21 chars. */ str = (char*)cJSON_malloc(2);
if (str) sprintf(str,"%d",item->valueint); }
} if (str)
else {
{ strcpy(str,"0");
if (p) str=ensure(p,64); }
else str=(char*)cJSON_malloc(64); /* This is a nice tradeoff. */ }
if (str) /* value is an int */
{ else if ((fabs(((double)item->valueint) - d) <= DBL_EPSILON) && (d <= INT_MAX) && (d >= INT_MIN))
if (d*0!=0) sprintf(str,"null"); /* This checks for NaN and Infinity */ {
else if (fabs(floor(d)-d)<=DBL_EPSILON && fabs(d)<1.0e60) sprintf(str,"%.0f",d); if (p)
else if (fabs(d)<1.0e-6 || fabs(d)>1.0e9) sprintf(str,"%e",d); {
else sprintf(str,"%f",d); str = ensure(p, 21);
} }
} else
return str; {
/* 2^64+1 can be represented in 21 chars. */
str = (char*)cJSON_malloc(21);
}
if (str)
{
sprintf(str, "%d", item->valueint);
}
}
/* value is a floating point number */
else
{
if (p)
{
/* This is a nice tradeoff. */
str = ensure(p, 64);
}
else
{
/* This is a nice tradeoff. */
str=(char*)cJSON_malloc(64);
}
if (str)
{
/* This checks for NaN and Infinity */
if ((d * 0) != 0)
{
sprintf(str, "null");
}
else if ((fabs(floor(d) - d) <= DBL_EPSILON) && (fabs(d) < 1.0e60))
{
sprintf(str, "%.0f", d);
}
else if ((fabs(d) < 1.0e-6) || (fabs(d) > 1.0e9))
{
sprintf(str, "%e", d);
}
else
{
sprintf(str, "%f", d);
}
}
}
return str;
} }
static unsigned parse_hex4(const char *str) static unsigned parse_hex4(const char *str)