Java中的舍入双精度 - 最小小数位数

时间:2012-03-19 20:10:43

标签: java format

  

可能重复:
  Round a double to 2 significant figures after decimal point

以下代码可以使用

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

2 个答案:

答案 0 :(得分:3)

这不符合您的预期,因为roundTwoDecimals()的返回值是double类型,它会丢弃您在函数中执行的格式设置。为了达到您的目的,您可以考虑从String返回roundTwoDecimals()表示。

答案 1 :(得分:0)

将格式化的数字转换回double会使您丢失所有格式更改。将功能更改为:

public static String roundTwoDecimals(double d) {   
    DecimalFormat twoDForm = new DecimalFormat("#.00");
    return twoDForm.format(d);
}
编辑:你是对的,“#。00”是正确的。

相关问题