Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

strange double to int conversion behavior in c++

The following program shows the weird double to int conversion behavior I'm seeing in c++:

#include <stdlib.h>
#include <stdio.h>

int main() {
  double d = 33222.221;
  printf("d = %9.9g\n",d);

  d *= 1000;
  int i = (int)d;

  printf("d = %9.9g | i = %d\n",d,i);

  return 0;
}

When I compile and run the program, I see:

g++ test.cpp
./a.out
d = 33222.221
d =  33222221 | i = 33222220

Why is i not equal to 33222221? The compiler version is GCC 4.3.0

like image 756
user924 Avatar asked Dec 07 '25 10:12

user924


1 Answers

Floating point representation is almost never precise (only in special cases). Every programmer should read this: What Every Computer Scientist Should Know About Floating-Point Arithmetic

In short - your number is probably 33222220.99999999999999999999999999999999999999999999999999999999999999998 (or something like that), which becomes 33222220 after truncation.

like image 62
viraptor Avatar answered Dec 10 '25 01:12

viraptor



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!