Why does the following code:
System.out.println((int)(19.99 * 100));
produce the result “1998”?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Rounding errors. If you look at the result of your calculation without the cast, you get:
So when you cast to int, the decimal part is dropped, not rounded up, and you get 1998.
The moral is, if you need an exact answer, don’t use float / double at all. If you’re talking about a discrete value like money, use int and deal with the atomic unit (eg. pence.) If you do need exact decimals, then
BigDecimalis your friend.While you can bodge the result here using
Math.round()to bring the result to where it’s expected, this won’t work in all cases and fails to address the underlying issue.