Floating point numbers are incapable of representing every real number to infinite precision. And 40.0
is no exception. Instead, if your calculation is done in a correct and numerically stable way, you'll get the closest number a double
can represent.
Functions like printf
make the output pretty by considering how close the operand they received is to a given number.
So your result may be 39.99998
, the closest number a double
can represent to your correct result. And it is shown as 40.0000000
.
However casting to an int
performs truncation. So it becomes 39
.
For your purposes (you seem to be dealing in money), an approach which will work best is to get rid of floating point numbers completely. You only need two integers. One for cents (which grows only up to 100), and one for dollars1.
1 I assume dollars and cents because of the multiplication by 100
in your code. Naturally it applies for any currency