2013-12-18 131 views
0

如何使浮點值僅顯示點和小數點(如果存在)。例如,顯示17而不是17.0,但如果我有17.2顯示點和小數。顯示並不顯示浮點值中的點和小數?

謝謝!

+5

http://stackoverflow.com/questions/703396/how-t鄰很好格式浮動號碼到字符串,而無需-不必要十進制-0/14126736#14126736 –

回答

0

您可能還需要限制小數部分的長度,因爲在執行一系列浮點運算後可能會出現類似12.00001的結果。代碼片段我用漂亮格式的雙轉換爲字符串:

private static final DecimalFormat[] formats= new DecimalFormat[]{ 
    null, 
    new DecimalFormat("#.#"), 
    new DecimalFormat("#.##"), 
    new DecimalFormat("#.###"), 
    new DecimalFormat("#.####") 
}; 

public static String toConciseString(double d, int fractionLength){ 
    long asLong = (long) d; 
    if(Math.abs(d - asLong) < 0.00001d){ 
     return Long.toString(asLong); 
    } 

    return formats[fractionLength].format(d); 
} 

測試用例顯示輸出的例子:

assertThat(toConciseString(23.323, 2)).isEqualTo("23.32"); 
assertThat(toConciseString(23.329, 2)).isEqualTo("23.33"); 
assertThat(toConciseString(23.329, 3)).isEqualTo("23.329"); 
assertThat(toConciseString(23.3, 2)).isEqualTo("23.3"); 
assertThat(toConciseString(23.30001, 2)).isEqualTo("23.3"); 
assertThat(toConciseString(23.00001, 2)).isEqualTo("23"); 
0

試試這個:

DecimalFormat decimalFormat = new DecimalFormat("#0.##"); 
    float float1 = 1.00f; 
    float float2 = 1.02f; 
    System.out.println(decimalFormat.format(float1)); 
    System.out.println(decimalFormat.format(float2)); 

它會打印出:

1 
1.02