2015-12-14 24 views
3

我想根據變量輸入獲取所需的輸出。我可以接近我想要的,但似乎有一個數字四捨五入的問題。僅在需要時顯示雙精度的小數(舍入問題)

我想通過示例(輸入>輸出)。

30 > 30 
30.0 > 30 
30.5 > 30,5 
30.5555 > 30,6 
30.04 > 30 

問題是,最後一個回來爲30.0。現在我明白了爲什麼發生這種情況(由於四捨五入向上/向下)

我的代碼:

private String getDistanceString(double distance) { 
     distance = 30.55; 
     DecimalFormat df = new DecimalFormat(".#"); 
     if (distance == Math.floor(distance)) { 
      //If value after the decimal point is 0 change the formatting 
      df = new DecimalFormat("#"); 
     } 
     return (df.format(distance) + " km").replace(".", ","); 
    } 
+1

你不需要更換得到一個逗號作爲小數點分隔符http://stackoverflow.com/q/5054132/995714 –

+0

@LưuVĩnhPhúc謝謝你的加入。這確實看起來更好。 –

回答

2

幾乎總是錯的使用==浮點數。您應該使用Math.abs(a - b) < x

private String getDistanceString(double distance) { 
    DecimalFormat df = new DecimalFormat(".#"); 
    if (Math.abs(distance - Math.round(distance)) < 0.1d) { 
     //If value after the decimal point is 0 change the formatting 
     df = new DecimalFormat("#"); 
    } 
    return (df.format(distance) + " km").replace(".", ","); 
} 

public void test() { 
    double[] test = {30d, 30.0d, 30.5d, 30.5555d, 30.04d, 1d/3d}; 
    for (double d : test) { 
     System.out.println("getDistanceString(" + d + ") = " + getDistanceString(d)); 
    } 
} 
+0

謝謝你解決了我的問題,實際上對我使用== –

+0

真的很遺憾,實際上它不是一個平等比較的好方法。 [浮點和雙精度比較的最有效方法](http://stackoverflow.com/q/17333/995714),[浮點精度指南比較](http://floating-point-gui.de/errors/comparison /) –

+0

我剛剛注意到,雖然它與我在我的問題中給出的示例一起工作,但如果輸入爲例如30.99,則輸出爲31,0,但它不會執行我想要的操作。這應該是31.我試着調整一下代碼,但得出的結論我不明白這足以做到這一點。你能進一步幫助我嗎? –

0

它周圍的黑客,是正則表達式替換

return 
     (""+df.format(distance)) 
     .replaceAll("\\.(0+$)?", ",") //replace . and trailing 0 with comma, 
     .replaceAll(",$","") //if comma is last char, delete it 
     + " km"; //and km to the string