The reason for this behaviour is that most floating point numbers can't be represented exactly.
2.09 is such a number. When converting the string to a single precision (
float
) the stored value is 2.089999914. So the result of the multiplication is 208.9999914. Because casting to
int
is just truncating, the result is 208.
Even using double precision (
double
) would not help because that can't store the exact value 2.09 too.
The solution is to use
round()
as suggested by CPallini or adding 0.5:
float floatResult = userNumber * n;
change = static_cast<int>(floatResult < 0 ? floatResult - 0.5f : floatResult + 0.5f);</int>
But note that the above should only be used when you know that the result will fit in an integer (does not generate an overflow).