Basically, I don’t understand why the code below will output 434 when 4.35 * 100 = 435.0 which is converted to the int of 435, right?
What is the simple explanation for this and is this an issue which crops up often?
How would you get around this?
public class RoundOffDemo {
public static void main(String[] args) {
double price = 4.35;
int cents = (int) (100 * price); // Should be 435
System.out.println(cents); // Prints 434!
}
}
The problem is that 4.35 cannot be exactly represented in binary. So 4.35 * 100 is not exactly 435.0. (Every fraction in binary is the sum of inverse powers of 2, all of which are terminating decimals. Unfortunately, 0.35 decimal has a non-terminating binary expansion. So 4.35 is more like 4.349999…x (where x is something beyond which everything is zero, courtesy of the machine’s finite representation of floating point numbers.) Integer truncation then produces 434. You can use
Math.round()to avoid this problem.