在Java中有三种取整方式:ceil、floor、round;
顾名思义:ceil是向上取整、floor是向下取整、round是四舍五入;
round的四舍五入算法是:加上0.5再向下取整。
附上代码说明:
public static void main(String[] args) {
double a = 1.2;
double b = 1.7;
double c = -1.2;
double d = -1.7;
System.out.println("Math.round : ");
System.out.println("a --> "+Math.round(a));
System.out.println("b --> "+Math.round(b));
System.out.println("c --> "+Math.round(c));
System.out.println("d --> "+Math.round(d));
System.out.println("Math.ceil : ");
System.out.println("a --> "+Math.ceil(a));
System.out.println("b --> "+Math.ceil(b));
System.out.println("c --> "+Math.ceil(c));
System.out.println("d --> "+Math.ceil(d));
System.out.println("Math.floor : ");
System.out.println("a --> "+Math.floor(a));
System.out.println("b --> "+Math.floor(b));
System.out.println("c --> "+Math.floor(c));
System.out.println("d --> "+Math.floor(d));
}
结果是:
Math.round :
a --> 1
b --> 2
c --> -1
d --> -2
Math.ceil :
a --> 2.0
b --> 2.0
c --> -1.0
d --> -1.0
Math.floor :
a --> 1.0
b --> 1.0
c --> -2.0
d --> -2.0