2016-11-04 77 views
0

我需要格式化此浮點數,以便標籤顯示x小數點。 ex.10.9832432我希望它顯示10.9832432確切的小數位數。如何在java中將浮點數設置爲x的小數位數

try{ 
    DecimalFormat df = new DecimalFormat("#"); 
    float numOne = Float.parseFloat(numberOne.getText()); 
    float numTwo = Float.parseFloat(numberTwo.getText()); 
    float anser = numOne+numTwo; 
    String AR = df.format(anser); 
     answerLabel.setText(AR); 
    }catch(NumberFormatException nfe){ 
     answerLabel.setText(null); 
    } 
+0

'float'只具有精度6位,我建議使用'double'或'BigDecimal' –

回答

0

那好吧....你應該告訴你的代碼不喜歡你和你的使用的DecimalFormatDF變量聲明做其顯示爲整數的字符串表示。

如果你想讓你的標籤顯示實際提供的浮點數,那麼除非你真的想要顯示一個實際的特定字符串格式,否則不要打擾使用DecimalFormat。下面將做需要什麼:

float numOne = Float.parseFloat(numberOne.getText()); 
    float numTwo = Float.parseFloat(numberTwo.getText()); 
    float anser = numOne+numTwo; 
    String AR = String.valueOf(anser); 
    answerLabel.setText(AR); 

但是,如果你要顯示一個特定的字符串格式(假設顯示總和的3個精確到小數點後),通過各種手段,請用DecimalFormat的但以這種方式:

try{ 
    DecimalFormat df = new DecimalFormat("#.###"); // provide the format you actually want. 
    float numOne = Float.parseFloat(numberOne.getText()); 
    float numTwo = Float.parseFloat(numberTwo.getText()); 
    float anser = numOne+numTwo; 
    String AR = df.format(anser); 
    answerLabel.setText(AR); 
} 
catch(NumberFormatException nfe){ 
    answerLabel.setText(null); 
} 
相關問題