Issue
For example, float a is 2.15, float b is 1.15, but a-b
will be 1.0000001
,
My first question is how to get the right answer 2.15-1.15=1
?
My second question is how to check the result of a minus b is an integer?
Solution
- You can either still using float and round the result, or use double instead.
- If you mean the result has no fraction (decimal part) you can check with
% 1 == 0
. It should give you true.
Something like:
public class MyClass {
public static void main(String args[]) {
double x = 2.15;
double y = 1.15;
double z = x - y;
System.out.println("Sum of x-y = " + z);
System.out.println("Sum of x-y = " + Math.round(z));
System.out.println("Sum of x-y = " + (z % 1 == 0));
}
}
Answered By - dk_016
Answer Checked By - Senaida (JavaFixing Volunteer)