mirror of
https://github.com/DaveGamble/cJSON.git
synced 2023-08-10 21:13:26 +03:00
reformatting: print_number
This commit is contained in:
parent
282006d918
commit
67845e3dc6
71
cJSON.c
71
cJSON.c
@ -274,28 +274,71 @@ static char *print_number(cJSON *item,printbuffer *p)
|
|||||||
{
|
{
|
||||||
char *str = 0;
|
char *str = 0;
|
||||||
double d = item->valuedouble;
|
double d = item->valuedouble;
|
||||||
|
/* special case for 0. */
|
||||||
if (d == 0)
|
if (d == 0)
|
||||||
{
|
{
|
||||||
if (p) str=ensure(p,2);
|
if (p)
|
||||||
else str=(char*)cJSON_malloc(2); /* special case for 0. */
|
|
||||||
if (str) strcpy(str,"0");
|
|
||||||
}
|
|
||||||
else if (fabs(((double)item->valueint)-d)<=DBL_EPSILON && d<=INT_MAX && d>=INT_MIN)
|
|
||||||
{
|
{
|
||||||
if (p) str=ensure(p,21);
|
str = ensure(p, 2);
|
||||||
else str=(char*)cJSON_malloc(21); /* 2^64+1 can be represented in 21 chars. */
|
|
||||||
if (str) sprintf(str,"%d",item->valueint);
|
|
||||||
}
|
}
|
||||||
else
|
else
|
||||||
{
|
{
|
||||||
if (p) str=ensure(p,64);
|
str = (char*)cJSON_malloc(2);
|
||||||
else str=(char*)cJSON_malloc(64); /* This is a nice tradeoff. */
|
}
|
||||||
if (str)
|
if (str)
|
||||||
{
|
{
|
||||||
if (d*0!=0) sprintf(str,"null"); /* This checks for NaN and Infinity */
|
strcpy(str,"0");
|
||||||
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);
|
/* value is an int */
|
||||||
|
else if ((fabs(((double)item->valueint) - d) <= DBL_EPSILON) && (d <= INT_MAX) && (d >= INT_MIN))
|
||||||
|
{
|
||||||
|
if (p)
|
||||||
|
{
|
||||||
|
str = ensure(p, 21);
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
/* 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;
|
return str;
|
||||||
|
Loading…
x
Reference in New Issue
Block a user