您可能会舍入错误,但是我在这里看不到它。
final double first=198.4;//value extract by unmodifiable format methodfinal double second=44701.2;//value extract by unmodifiable format methodfinal double firstDifference= first+second; //I receive 44899.6final double calculatedDifference=44900.1; // comparison value for the flowfinal double error=firstDifference-calculatedDifference;// I receive -0.5if(Math.abs(error)<=0.5d){ // this branch is entered. System.out.println(error);}版画
-0.5
有两种方法可以更一般地处理此问题。您可以定义一个舍入误差,例如
private static final double ERROR = 1e-9; if(Math.abs(error)<=0.5d + ERROR){或使用舍入
final double firstDifference= round(first+second, 1); // call a function to round to one decimal place.
或使用固定精度的整数
final int first=1984;// 198.4 * 10final int second=447012; // 44701.2 * 10final int firstDifference= first+second; //I receive 448996final int calculatedDifference=449001; // comparison value for the flowfinal int error=firstDifference-calculatedDifference;// I receive -5if(Math.abs(error)<=5){ // this branch is entered. System.out.println(error);}或者您可以使用BigDecimal。这通常是许多开发人员的首选解决方案,但恕我直言。;)



