Search code examples
javaprimitive

Doing double - int in java


For example if I do this:

double decPart = 5.57 - 5;
System.out.println(decPart);

it returns 0.5700000000000003, instead of just 0.57. I can print it out properly using System.out.printf("%.2f", decPart), but that doesn't solve the problem (Note: the decimal part is not necessarily 2 decimal places). So for example if I try to do this:

System.out.println(1.0 - decPart);

it would return 0.4299999999999997

Can somebody please explain this behavior and how to fix it. Thanks in advance.


Solution

  • This is due to floating point imprecision. Floating-point numbers (float, double in Java) cannot represent some numbers exactly. If you're looking for absolute precision, look into BigDecimal.