You may get a rounding error, but I do not see it here.
final double first=198.4;//value extract by unmodifiable format method final double second=44701.2;//value extract by unmodifiable format method final double firstDifference= first+second; //I receive 44899.6 final double calculatedDifference=44900.1; // comparison value for the flow final double error=firstDifference-calculatedDifference;// I receive -0.5 if(Math.abs(error)<=0.5d){ // this branch is entered. System.out.println(error); }
prints
-0.5
There are two ways to deal with this more generally. You can define a rounding error such as
private static final double ERROR = 1e-9; if(Math.abs(error)<=0.5d + ERROR){
OR use rounding
final double firstDifference= round(first+second, 1); // call a function to round to one decimal place.
OR use fixed-precision integers
final int first=1984;// 198.4 * 10 final int second=447012; // 44701.2 * 10 final int firstDifference= first+second; //I receive 448996 final int calculatedDifference=449001; // comparison value for the flow final int error=firstDifference-calculatedDifference;// I receive -5 if(Math.abs(error)<=5){ // this branch is entered. System.out.println(error); }
OR You can use BigDecimal. This is often the preferred solution for many developers, but the latest version is IMHO.;)
source share