First: it is a warning, not an error. But if you treat warnings like errors like a good coder should ;) then I commend you good sir.
Let's look at this line:
value2 = (value1 * .001);
value1 is declared as an int.
value2 is declared as an int.
.001 is a floating point number; a double to be precise.
An int (integer) is a whole number, like 1, 2, -5 or 1000. Fractional numbers like 1.1, 3.14 100.0000001 are not integers.
Computers and floating point math have gotchas. For example, take the number represented by (1/3). In our base-10 system, the closest we can get is 0.333333 with an eternal amount of 3s behind it. The computer has the same sort of problem, but it thinks in base-2; meaning the problem is the same but the practical cases are different. Depending on the sort of floating point and its accuracy, it is very well possible that a float cannot properly represent an integer despite it being in its 'range'!
In practice, this difference is miniscule and won't affect you, but it is a very nasty hole, which is the reason the warning exists. And now you know why you get an error here.
There will be values passed for which the result of the calculation cannot be converted to an integer without losing the fractional part.
In your case, there is probably no harm in rounding down like a proper bank would no doubt do. As such, your solution is:
value2 = (int)(value1 * .001);
This tells the compiler that you knowingly throw away the fractional part and that you really want an int out of the double that was given to you. |