2015-09-04 47 views
0

我正在測試javaFX中進度條/指標的功能,當我爲該指標添加特定值時,它會顯示一個奇怪的和意外的行爲。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 

很顯然,我希望它得到100%的10次按壓而不是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(); 
} 
+1

可能重複的[如何比較Java中的兩個double值?](http://stackoverflow.com/questions/8081827/how-to-compare-two-double-values-in-java) – Buddy

回答

3

你實際上是有效地達到100%,在10按下按鈕,它是導致它成爲.9999999而不是1浮點數的只是不準確。

有關浮點數爲何導致精度下降(「舍入誤差」)的更多信息,請參見this Stack Overflow thread

一個簡單的方法來解決這個問題,而不是使用double追蹤0和1之間的進度百分比,使用int追蹤0和100之間的整數進度不從精度問題的影響浮點類型如double s。如果您需要在此之外的函數中使用進度編號,該函數的值在0和1之間,則始終可以將您的int轉換爲double,並在該點除以100。