double multiplication error

I'm not sure if I'm doing something completely wrong or if this is an error in Dev C++ but cents SHOULD cout as 9, but its coming out as 8.

double fractPart = .09;
cents = static_cast<int>(fractPart * 100.00);
cout << "cents " << cents << endl;

some test outputs:
.00 works
.03 becomes 2
.06 becomes 5
.09 becomes 8
.12 becomes 11
.21 becomes 20
.30 becomes 29
.33 works
.60 becomes 59
.66 works
.71 becomes 70
.90 works
.99 becomes 98

does anyone know whats going on here? Maybe it has something to do with the static cast or rounding the double
floating point numbers can not represent all number exactly so you might have small rounding errors. .09*100.00 might be slightly less than 9. When you convert the number to an int you just throw away the fractional part. You could try to round the number before casting.
cents = static_cast<int>(round(fractPart * 100.00));
Last edited on
that fixed it thank you so much I was going mad
Topic archived. No new replies allowed.