java取整和java四舍五入方法 BigDecimal.setScale()方法详解

时间:2022-12-05 19:30:38
import java.math.BigDecimal;

public class TestGetInt {
    public static void main(String[] args) {
        double i = 2, j = 2.1, k = 2.5, m = 2.9;
        System.out.println("舍掉小数取整:Math.floor(2)=" + (int) Math.floor(i));//2
        System.out.println("舍掉小数取整:Math.floor(2.1)=" + (int) Math.floor(j));//2
        System.out.println("舍掉小数取整:Math.floor(2.5)=" + (int) Math.floor(k));//2
        System.out.println("舍掉小数取整:Math.floor(2.9)=" + (int) Math.floor(m));//2


        System.out.println("四舍五入取整:(2)=" + new BigDecimal("2").setScale(0, BigDecimal.ROUND_HALF_UP));//2
        System.out.println("四舍五入取整:(2.1)=" + new BigDecimal("2.1").setScale(0, BigDecimal.ROUND_HALF_UP));//2
        System.out.println("四舍五入取整:(2.5)=" + new BigDecimal("2.5").setScale(0, BigDecimal.ROUND_HALF_UP));//3
        System.out.println("四舍五入取整:(2.9)=" + new BigDecimal("2.9").setScale(0, BigDecimal.ROUND_HALF_UP));//3

        System.out.println("凑整:Math.ceil(2)=" + (int) Math.ceil(i));//2
        System.out.println("凑整:Math.ceil(2.1)=" + (int) Math.ceil(j));//3
        System.out.println("凑整:Math.ceil(2.5)=" + (int) Math.ceil(k));//3
        System.out.println("凑整:Math.ceil(2.9)=" + (int) Math.ceil(m));//3

        System.out.println("舍掉小数取整:Math.floor(-2)=" + (int) Math.floor(-i));//-2
        System.out.println("舍掉小数取整:Math.floor(-2.1)=" + (int) Math.floor(-j));//-3
        System.out.println("舍掉小数取整:Math.floor(-2.5)=" + (int) Math.floor(-k));//-3
        System.out.println("舍掉小数取整:Math.floor(-2.9)=" + (int) Math.floor(-m));//-3

        System.out.println("四舍五入取整:(-2)=" + new BigDecimal("-2").setScale(0, BigDecimal.ROUND_HALF_UP));//-2
        System.out.println("四舍五入取整:(-2.1)=" + new BigDecimal("-2.1").setScale(0, BigDecimal.ROUND_HALF_UP));//-2
        System.out.println("四舍五入取整:(-2.5)=" + new BigDecimal("-2.5").setScale(0, BigDecimal.ROUND_HALF_UP));//-3
        System.out.println("四舍五入取整:(-2.9)=" + new BigDecimal("-2.9").setScale(0, BigDecimal.ROUND_HALF_UP));//-3

        System.out.println("凑整:Math.ceil(-2)=" + (int) Math.ceil(-i));//-2
        System.out.println("凑整:Math.ceil(-2.1)=" + (int) Math.ceil(-j));//-2
        System.out.println("凑整:Math.ceil(-2.5)=" + (int) Math.ceil(-k));//-2
        System.out.println("凑整:Math.ceil(-2.9)=" + (int) Math.ceil(-m));//-2
    }
}

结果

舍掉小数取整:Math.floor(2)=2
舍掉小数取整:Math.floor(2.1)=2
舍掉小数取整:Math.floor(2.5)=2
舍掉小数取整:Math.floor(2.9)=2
四舍五入取整:(2)=2
四舍五入取整:(2.1)=2
四舍五入取整:(2.5)=3
四舍五入取整:(2.9)=3
凑整:Math.ceil(2)=2
凑整:Math.ceil(2.1)=3
凑整:Math.ceil(2.5)=3
凑整:Math.ceil(2.9)=3
舍掉小数取整:Math.floor(-2)=-2
舍掉小数取整:Math.floor(-2.1)=-3
舍掉小数取整:Math.floor(-2.5)=-3
舍掉小数取整:Math.floor(-2.9)=-3
四舍五入取整:(-2)=-2
四舍五入取整:(-2.1)=-2
四舍五入取整:(-2.5)=-3
四舍五入取整:(-2.9)=-3
凑整:Math.ceil(-2)=-2
凑整:Math.ceil(-2.1)=-2
凑整:Math.ceil(-2.5)=-2
凑整:Math.ceil(-2.9)=-2