-4
int a = atof("4.60") * 100;
int b = atof("6.60") * 100;
printf("a:%d",a); //<==== here print a:459
printf("b:%d",b); //<==== here print b:660

In IEEE 754, 4.60 is 4.599999999... and 6.60 is 6.5999999... I expect print b will show 659 too. How does the truncate work?

1 Answers1

0

As you noted 6.6 in the source code is not exactly 6.6 but rather is 6.5999999999999996447286321199499070644378662109375. Similarly, 4.6 produces 4.5999999999999996447286321199499070644378662109375.

When you multiply by 100, there is another rounding error, as the new value is not exactly representable in floating-point and must be rounded to the nearest representable value.

For 6.6 * 100, the nearest representable value is 660.

For 4.6 * 100, the nearest representable value is 459.99999999999994315658113919198513031005859375.

Eric Postpischil
  • 195,579
  • 13
  • 168
  • 312