如何在java中将浮点数格式化为x小数位数

时间:2016-11-04 17:47:45

标签: java decimalformat

我需要格式化此浮点数,因此标签将显示x小数位数。 ex.10.9832432我希望它显示10.9832432确切的小数位数。

    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);
    }

1 个答案:

答案 0 :(得分:0)

那么......你应该告诉你的代码不要将它显示为整数的字符串表示形式,就像使用 dfalFormat > df 变量声明一样。强>上课。

如果您希望标签显示实际提供的浮动总和,那么除非您真的想要显示实际的特定字符串格式,否则不要再使用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);
}