image.png

    1.使用java.math.BigDecimal

    1. double d = 2.345;
    2. BigDecimal bigDecimal = new BigDecimal(d);
    3. //四舍五入了
    4. BigDecimal bigDecimal1 = bigDecimal.setScale(2, RoundingMode.HALF_UP);
    5. System.out.println(bigDecimal1);//2.35

    2.使用java.text.DecimalFormat

    1. double ave = 109.3456;
    2. //四舍五入了
    3. DecimalFormat df = new DecimalFormat("#.00");
    4. System.out.println(df.format(ave));//109.23

    3.使用java.text.NumberFormat

    1. double ave1 = 109.3456;
    2. NumberFormat nf = NumberFormat.getNumberInstance();
    3. nf.setMaximumFractionDigits(2);
    4. nf.setRoundingMode(RoundingMode.HALF_UP);
    5. nf.setGroupingUsed(false);
    6. System.out.println(nf.format(ave1));//109.35

    4.使用java.util.Formatter

    1. double ave2 = 109.3456;
    2. String s = new Formatter().format("%.2f", ave2).toString();
    3. System.out.println(s);//109.35

    5.使用String.format(推荐)

    1. double ave3 = 109.3456;
    2. System.out.println(String.format("%.2f",ave3));//109.35