double cost = 10.95;
int numDollars = (int) cost; //sets numDollars to 10
If your intent was to round cost to the nearest dollar, you needed to write
int numDollars = (int)(cost+0.5); //numDollars has value 11
Above is what's written in my AP computer science A Barron's book. I'm quite new to Java and all, but I was just wondering if the 0.5's should be replaced with 0.05's. If the book is right though, could someone help me understand why?
The example uses 10.95, but the solution needs to work for all values.
Consider a different example using 10.51
What should the right answer be? 11
But how do you get there?
10.51 + 0.50 = 11.01, truncated by typecast to 11
If we tried to use your suggestion, we would get:
10.51 + 0.05 == 10.56, truncated by typecast to 10 Wrong Answer