int/double类型相除保留两位小数

方案1:使用DecimalFormat进行格式化

方案1:使用String类型格式转换

public class Variable {

    public static void main(String[] args) {
        int a = 2;
        int b = 3;
        int c = a / b;
        double d = (double) a / b; //
        System.out.println(c);
        DecimalFormat format = new DecimalFormat("0.00");
        System.out.println(format.format(d));
        //%.2f  %.表示 小数点前任意位数   2 表示两位小数 格式后的结果为f 表示浮点型
        System.out.println(String.format("%.2f", d));  
        double g=1.2;
        double h=2.5;
        double k=h/g;//如果两个浮点数都有很多位数,那就转BigDecimal进行运算
        System.out.println(format.format(k));
    }

猜你喜欢

转载自blog.csdn.net/m1234ilu/article/details/82976156