I tried running the following code:
double f = 4.35;
int n = (int) (100 * f);
n will be 434. Why?
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.
4.35 cannot be represented exactly as a floating-point number since .35 is not a (negative) power of 2. As a result, there’s a bit of roundoff one way or another. There will probably also be roundoff when you multiply by 100. If the resulting number is a bit less than 435, casting to int will take the floor of it, which is 434.
If you’d like to round to the NEAREST integer, you can add 0.5 to the result and then cast to int. This is the most general way to round numbers, although Java has a built-in implementation of rounding.