I have a stock selling/buying program, where the user can say how much of a stock they wish to buy and sell. Everything works fine, until the user wants to sell a stock for $4.10 for $5.10. In order to do math easier with the floating point, I convert the double to an int: 10.10 becomes 1010, and so on. Whenever I cast 4.10 to an int, it becomes 409, and the same occurs for 5.10.
The money is stored in a class, Dollars. Inside of this class, when I call a constructor, I can either call Dollars(int cents): cents(cents) {}
or Dollars(double dollars): cents(0) { *this = dollars; }
. When the double constructor is used, it uses the following cents = (int)(dollars * 100.0);
to cast the given double into an int.
I've tried using the (int)(double)
cast method inside the class to convert into an int, and I've also tried casting into an int before, and using the int constructor, but neither have worked.
I expect the output of this cast to be 410 when I feed it 4.10, but it always comes out to 4.09.