我正在测试javaFX中进度条/指示器的功能,当我向指示器添加特定值时,它会显示一个奇怪且意外的行为。
public class RunningController {
public ProgressIndicator progressCircle;
//This Adds value to the progress indicator
private double addProgess(){
double newProgress, currentProgress;
currentProgress = progressCircle.getProgress();
System.out.println("Current Process "+ currentProgress);
newProgress = currentProgress + 0.1;
System.out.println("New Progress " + newProgress);
return newProgress;
}
//This is tied to a single button press to update the indicator
public void progressCircleMethod(ActionEvent actionEvent) {
checkProgress();
}
//This checks the value of the progress indicator and adds if required
private void checkProgress() {
if (progressCircle.getProgress() < 1){
progressCircle.setProgress(addProgess());
} else {
System.out.println("Complete");
}
}
}
当我完成此操作时,我会将一些有趣的值输出到控制台:
//Button Clicked (1)
Current Process 0.0
New Progress 0.1
//Button Clicked (2)
Current Process 0.1
New Progress 0.2
//Button Clicked (3)
Current Process 0.2
New Progress 0.30000000000000004
//Button Clicked (4)
Current Process 0.30000000000000004
New Progress 0.4
//Button Clicked (5)
Current Process 0.4
New Progress 0.5
//Button Clicked (6)
Current Process 0.5
New Progress 0.6
//Button Clicked (7)
Current Process 0.6
New Progress 0.7
//Button Clicked (8)
Current Process 0.7
New Progress 0.7999999999999999
//Button Clicked (9)
Current Process 0.7999999999999999
New Progress 0.8999999999999999
//Button Clicked (10)
Current Process 0.8999999999999999
New Progress 0.9999999999999999
//Button Clicked (11)
Current Process 0.9999999999999999
New Progress 1.0999999999999999
显然,我希望在10台印刷机中达到100%,而不是11 为什么按下按钮(3)和(8)时会添加这些额外的十进制值?
编辑:完全忘记了关于双打的四舍五入问题。我可以使用接受的答案或使用BigDecimal
。使用BigDecimal
:
private double addProgess(){
double currentProgress = progressCircle.getProgress();
BigDecimal currentProgressValue;
BigDecimal newProgressValue;
currentProgressValue = BigDecimal.valueOf(currentProgress);
System.out.println("Current Progress " + currentProgressValue);
newProgressValue = currentProgressValue.add(BigDecimal.valueOf(0.1d));
System.out.println("New Progress " + newProgressValue);
return newProgressValue.doubleValue();
}
答案 0 :(得分:3)
您实际上在10次按下按钮时实际达到100%,这只是浮点数的不准确性导致它.9999999
而不是1
。
有关浮点数导致精度损失(“舍入错误”)的原因的更多信息,请参阅this Stack Overflow thread。
解决此问题的一种简单方法是使用double
来跟踪0到1之间的进度,而不是使用int
来跟踪0到100之间的进度。整数不会受到影响来自像double
这样的浮点类型的精度问题。如果您需要在此之外的函数中使用进度号,该函数需要0到1之间的值,则可以始终将int
强制转换为double
并将其除以100。< / p>