java (JDK 1.4) 中十进制数的管理有问题。
我有两个双数第一个和第二个(作为格式化String的输出)。我在拳头和秒之间求和,我收到一个带有更多小数位数的数字!
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.598 instead of 44899.6
final double calculatedDifference=44900.1; // comparison value for the flow
final double error=firstDifference-calculatedDifference;// I receive -0.50390605 instead 0.5
if(Math.abs(error)<=0.5d)){
//I must enter in this branch but the error not allows the correct flow!!!
}
/***
* the flow of program is uncorrect and there's a very visible bug in business view
*/
我不喜欢增加阈值(0.5d),因为在类似的情况下我不安全(当我开始编码时,规范将0.1d作为比较值)。如果它是唯一的解决方案,0.9d的值是这个问题的最安全值吗?
我该如何解决这种情况?我认为这个问题是通过使用双变量得出的,但是对于浮点数我有同样的问题。
一些想法(如果可能的话,有一些经过测试的代码行;))?