2012-03-19 69 views
2

可能重複:
Round a double to 2 significant figures after decimal point四捨五入雙Java中 - 最少小數位數

下面的代碼工作

import java.text.DecimalFormat; 

public class Test { 
public static void main(String[] args){ 

    double x = roundTwoDecimals(35.0000); 
    System.out.println(x); 
} 

public static double roundTwoDecimals(double d) { 
    DecimalFormat twoDForm = new DecimalFormat("#.00"); 
    twoDForm.setMinimumFractionDigits(2); 
    return Double.valueOf(twoDForm.format(d)); 
} 
} 

它導致35.0。 如何強制最小小數位數? 我想要的輸出是35.00

+5

尾隨零的數量不是'double'的財產,這是一個'String'表示的屬性。 – 2012-03-19 20:14:17

+0

http://stackoverflow.com/a/7593617/446885 – Shahzeb 2012-03-19 20:15:17

+0

如何做到這一點而不轉換爲字符串? – 2012-03-19 20:15:45

回答

3

這不像你期望的那樣工作,因爲roundTwoDecimals()的返回值是double,它丟棄了你在函數中做的格式。爲了達到您想要的效果,您可以考慮返回roundTwoDecimals()String表示。

0

轉換格式的數字回到double會讓你失去所有的格式更改。更改功能爲:

public static String roundTwoDecimals(double d) { 
    DecimalFormat twoDForm = new DecimalFormat("#.00"); 
    return twoDForm.format(d); 
} 

編輯:你說得對,「#.00」是正確的。

+0

事實上,'###'將使小數可選,這似乎並沒有成爲他想要的東西。有關返回String的建議是相關的部分。 – VeeArr 2012-03-19 20:21:20