您可以获得舍入错误,但我在这里看不到它.
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);
}
版画
-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 * 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);
}
或者您可以使用BigDecimal.这通常是许多开发人员的首选解决方案,但最后一个选项是恕我直言. 😉