向上取整

第一种:ceil 函数

ceil 是天花板的意思,表示向上取整。 测试:

  1. System.out.println(Math.ceil(1.01));
  2. System.out.println(Math.ceil(-1.01));
  3. System.out.println(Math.ceil(1.5));
  4. System.out.println(Math.ceil(-1.5));

输出结果:

  1. 2.0
  2. -1.0
  3. 2.0
  4. -1.0

第二种:三目运算符

  1. x / y + (x % y == 0 ? 0 : 1);

向下取整

第二种:floor 是地板的意思,表示向下取整。 测试:

  1. System.out.println(Math.floor(1.01));