static_cast<int> function

double amount;

int remainingAmount = static_cast<int(amount * 100);

static_cast assigns the result as 3486 not 3487

whereas it does assign correctly for other values, e.g.,

24.87; 2487; static_cast 2487,
44.87; 4487; static_cast 4487,

why can it be so?


It's to do with the representation of floating point numbers. They are stored as binary fractions and cannot represent every real number.

If you cout your amount variable to 16 decimal places, you will see how your problem evolves.

When you initialise a FP number, you typically get the number you want plus or minus a very small amount.

Check out the epsilon value on this page.


PS Please always use code tags when you post any code. Use the <> button on the right on the format menu.
Topic archived. No new replies allowed.