我想根據變量輸入獲取所需的輸出。我可以接近我想要的,但似乎有一個數字四捨五入的問題。僅在需要時顯示雙精度的小數(舍入問題)
我想通過示例(輸入>輸出)。
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(".", ",");
}
你不需要更換得到一個逗號作爲小數點分隔符http://stackoverflow.com/q/5054132/995714 –
@LưuVĩnhPhúc謝謝你的加入。這確實看起來更好。 –