使double保留两位小数的多方法 java保留两位小数

  1. 使用java.text.DecimalFormat
  2. 使用java.math.BigDecimal
  3. 使用java.text.NumberFormat
  4. 使用java.util.Formatter
  5. 使用String.format

方法一:DecimalFormat

double d1 = 3.23456;
double d2 = 5.73956;
double d3 = 0.0;
double d4 = 2.0;

public static String format1(double value) {
        DecimalFormat df = new DecimalFormat("0.00");
        return df.format(value);
}

//format输出的结果分别是:

 3.23
 5.74
 0.00
 2.00

// 0.00 表示两位小数 0.0000四位小数 以此类推...  

方法二:BigDecimal

double d1 = 3.23456;
double d2 = 5.73956;
double d3 = 0.0;
double d4 = 2.0;


public static String format2(double value) {
        BigDecimal bd = new BigDecimal(value);
        bd = bd.setScale(2, RoundingMode.HALF_UP);
        return bd.toString();
}

//format输出的结果分别是:
3.23
5.74
0.0
2.0

//从结果可以看出采用的是四舍五入的方式

方法三:NumberFormat

double d1 = 3.23456;
double d2 = 5.73956;
double d3 = 0.0;
double d4 = 2.0;

  public static String format3(double value) {

        NumberFormat nf = NumberFormat.getNumberInstance();
        nf.setMaximumFractionDigits(2);
         /*
          * setMinimumFractionDigits设置成2
          * 如果不这么做,那么当value的值是100.00的时候返回100
          * 而不是100.00
          */
        nf.setMinimumFractionDigits(2);
        nf.setRoundingMode(RoundingMode.HALF_UP);
         /*
          * 如果想输出的格式用逗号隔开,可以设置成true
          */
        nf.setGroupingUsed(false);
        return nf.format(value);
    }

//format输出的结果分别是:

3.23
5.74
0.00
2.00

方法四:Formatter

double d1 = 3.23456;
double d2 = 5.73956;
double d3 = 0.0;
double d4 = 2.0;

 public static String format4(double value) {
         /*
          * %.2f % 表示 .小数点前任意位数;2表示两位小数;格式后的结果为 f 表示浮点型
          */
        return new Formatter().format("%.2f", value).toString();
    }

//format输出的结果分别是:

3.23
5.74
0.00
2.00

方法五:String.format

double d1 = 3.23456;
double d2 = 5.73956;
double d3 = 0.0;
double d4 = 2.0;

public static String format5(double value) {
        return String.format("%.2f", value).toString();
    }
//format输出的结果分别是:

3.23
5.74
0.00
2.00

猜你喜欢

转载自blog.csdn.net/hzw2017/article/details/80275314