java 两个整数相除保留两位小数

1 第一种

import java.math.BigDecimal;

/**
 * @author WGR
 * @create 2020/3/17 -- 15:51
 */
public class DemoTest {

    public static void main(String[] args) {
        int a=100;
        int b=33;
        double f1 = new BigDecimal((float)a/b).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
        System.out.println(f1);
    }
}

 2 第二种

import java.text.DecimalFormat;

/**
 * @author WGR
 * @create 2020/3/17 -- 15:51
 */
public class DemoTest {

    public static void main(String[] args) {
        int a=100;
        int b=33;
        DecimalFormat df = new DecimalFormat("0.00");//格式化小数
        String num = df.format((float)a/b);//返回的是String类型
        System.out.println(num);
    }
}

发布了407 篇原创文章 · 获赞 2 · 访问量 6780

猜你喜欢

转载自blog.csdn.net/qq_29860591/article/details/104936365