|
Minor bug in float to string conversion January 12, 2014 05:34PM |
Registered: 12 years ago Posts: 157 |
// Float to a string.
static long precision[] = {0,10,100,1000,10000,100000,1000000,10000000,100000000};
char scratchString[STRING_LENGTH];
char* ftoa(char *a, float f, int prec)
{
if(a == NULL)
a = scratchString;
char *ret = a;
long whole = (long)f;
if(!whole && f < 0.0)
{
a[0] = '-';
a++;
}
snprintf(a, STRING_LENGTH, "%d", whole);
while (*a != '\0') a++;
*a++ = '.';
long decimal = abs((long)((f - (float)whole) * precision[prec]));
snprintf(a, STRING_LENGTH, "%d", decimal);
return ret;
}
My translation:// Float to a string. static const char *formatting[] = {"%d", "%d", "%02d","%03d","%04d","%05d","%06d","%07d","%08d"}; static long precision[] = {0,10,100,1000,10000,100000,1000000,10000000,100000000}; char scratchString[STRING_LENGTH]; char* ftoa(char *a, float f, int prec) { if(a == NULL) a = scratchString; char *ret = a; long whole = (long)f; if(!whole && f < 0.0) { a[0] = '-'; a++; } snprintf(a, STRING_LENGTH, "%d", whole); while (*a != '\0') a++; *a++ = '.'; long decimal = abs((long)((f - (float)whole) * precision[prec])); snprintf(a, STRING_LENGTH, formatting[prec], decimal); return ret; }The bug is a bit hard to trigger on the printer,
$ ./ftoa Old ftoa with input 0.000 and precision 2: 0.0 Old ftoa with input 0.090 and precision 2: 0.9 Old ftoa with input 0.123 and precision 2: 0.12 New ftoa with input 0.000 and precision 2: 0.00 New ftoa with input 0.090 and precision 2: 0.09 New ftoa with input 0.123 and precision 2: 0.12There are warnings about the %d in combination with 'long int',
$ gcc ftoa.c -o ftoa ftoa.c:23:3: warning: format ‘%d’ expects argument of type ‘int’, but argument 4 has type ‘long int’ [-Wformat] ftoa.c:27:3: warning: format ‘%d’ expects argument of type ‘int’, but argument 4 has type ‘long int’ [-Wformat] ftoa.c:44:3: warning: format ‘%d’ expects argument of type ‘int’, but argument 4 has type ‘long int’ [-Wformat]
|
Re: Minor bug in float to string conversion January 12, 2014 05:50PM |
Registered: 12 years ago Posts: 578 |
|
Re: Minor bug in float to string conversion January 12, 2014 06:04PM |
Registered: 15 years ago Posts: 1,236 |
snprintf(a, STRING_LENGTH, "%0*d", prec, decimal)
|
Re: Minor bug in float to string conversion January 12, 2014 06:09PM |
Registered: 12 years ago Posts: 157 |
|
Re: Minor bug in float to string conversion January 13, 2014 07:04AM |
Registered: 12 years ago Posts: 14,691 |
|
Re: Minor bug in float to string conversion January 13, 2014 07:13AM |
Registered: 15 years ago Posts: 1,612 |