2014-09-05 29 views
0

以下代碼上的雙值

private double roundTheReading(double toRoundValue) { 
    double roundetValue = 0; 
    if (formatter == null){ 
    DecimalFormatSymbols dfs = new DecimalFormatSymbols(); 
    dfs.setDecimalSeparator('.'); 
    formatter = new DecimalFormat(("#0." + zerosAfterDot),dfs); 
    } 
    roundetValue = Double.parseDouble(formatter.format(toRoundValue)); 
    return roundetValue; 
} 

否pointation使得雙「toRoundValue」的短路,因爲它富人9後點的字符和我需要僅0,1或它們(2被設置通過輸入法輸入零點後)。

問題是:如果zerosAfterDot爲「0」,答案應該是5或3421。每次1零(5.0 3421.0)。

劑量這有什麼做的線:

formatter = new DecimalFormat(("#0." + zerosAfterDot),dfs); 

是在這條線的點的點我在輸出得到什麼?如果是這樣,我可以使If()檢查點的值是否爲零。但我寧願不這樣做,因爲如果零後零> 0,它也會殺死點。我想繞過許多if語句。

TL,DR我該如何擺脫「。」當我沒有數字後面那個重要?

+0

可能重複[如何很好地格式化浮點數爲String避免不必要的小數0?(http://stackoverflow.com/questions/703396/how-to-nicely -format-floating-numbers-to-string-without-unnecessary-decimal-0) – icza 2014-09-05 10:11:17

回答

0

您可能正在顯示從roundTheReading返回的double值,該值始終包含非有效數字。相反,你可以返回一個String和使用的

formatter = new DecimalFormat(("0.#"); 
+0

該值用於其他方式,因此字符串返回不是最好的方式,因爲每次我想要使用時都需要將其返回。它。但我可以在UI中給getter方法中的字符串。它只是一個簡單的答案,我沒有想到,直到我看到你的。感謝那! – Fulli 2014-09-05 10:23:28