Thread: float to double conversion

1. float to double conversion

Given the following

Code:
```include <stdio.h>

int main(void)
{
int part1, part4;
float part2;
char part3[6];
char s[]="1234.56abc  903";

sscanf(s, "%2d%5e%5s%d", &part1, &part2, part3, &part4);
printf("parse string: %s\n", s);
printf("part1=%d\n", part1);
printf("part2=%f\n", part2);
printf("part3=%s\n", part3);
printf("part4=%d\n", part4);

return 0;

}```
The corresponding output is:
\$./fl
parse string: 1234.56abc 903
part1=12
part2=34.560001
part3=abc
part4=903

The way I've always understood it, the 1 in part2 appears because the conversion from binary to decimal is only exact when dealing with a power of 2. This includes fractional parts.

Now I change float to double

Code:
```#include <stdio.h>

int main(void)
{
int part1, part4;
double part2;
char part3[6];
char s[]="1234.56abc  903";

sscanf(s, "%2d%5le%5s%d", &part1, &part2, part3, &part4);
printf("parse string: %s\n", s);
printf("part1=%d\n", part1);
printf("part2=%f\n", part2);
printf("part3=%s\n", part3);
printf("part4=%d\n", part4);

return 0;

}```
The corresponding output is now:
\$./fl
parse string: 1234.56abc 903
part1=12
part2=34.560000
part3=abc
part4=903

The question is why doesn't the 1 appear in part 2 anymore? Is this because double has a longer precision? If I would have the computer print out the decimal spot to say 16 spots, would the 1 appear again?

2. Never mind. I decided to try something really radical and have my computer print 17 decimal spots to see if the precision error would arise.

Code:
```#include <stdio.h>

int main(void)
{
int part1, part4;
double part2;
char part3[6];
char s[]="1234.56abc  903";

sscanf(s, "%2d%20le%5s%d", &part1, &part2, part3, &part4);
printf("parse string: %s\n", s);
printf("part1=%d\n", part1);
printf("part2=%.17f\n", part2);
printf("part3=%s\n", part3);
printf("part4=%d\n", part4);

return 0;

}```
The output:
\$./fl
parse string: 1234.56abc 903
part1=12
part2=34.56000000000000227
part3=abc
part4=903

It does.

3. This is because something like 0.2 cannot be represented accurately in binary (ie. base 2), resulting in something like 0.199999999999527 or 0.20000000000105. Try representing 0.2 as a sequence of binary fractions (ie sum of 1/(2^k) ) and you'll find yourself with a troublesome infinite expansion. Don't count on floating-point numbers for total precision.

Popular pages Recent additions