java中向上向下及四舍五入取整的方法,double型强制转换成int型的取整方法?

向上取整:Math.ceil(double a)
向下取整:Math.floor(double a)
四舍五入取整:Math.round(double a)
这里要注意Math.round(double a)和Math.rint(double a),四舍五入取整要用Math.round(double a),千万不要用Math.rint(double a),后面我会再详细写Math.round(double a)和Math.rint(double a)的区别
例子1(三种取整的方法):

  double a = 35;
  double b = 20;
  double c = a/b; //等于1.75
  System.out.println(c);   //输出1.75
  System.out.println(Math.ceil(c)); //向上取整输出2.0
  System.out.println(Math.floor(c));  //向下取整输出1.0
  System.out.println(Math.round(c));  //四舍五入取整输出2.0

例子2(double型强制转换成int型):

  double d = 5.5;  
  int i = (int)d;  
  System.out.println("i=:"i);  //输出5

  double b = 5.9;  
  int i1 = (int)b;  
  System.out.println("i1=:"i1);  //输出5

  double c = 5.2;  
  int i2 = (int)c;  
  System.out.println("i2=:"i2); //输出5

你可能感兴趣的:(Android,技术)