类型转换截尾与舍入

如果将一个浮点数转化为整数的话,Java会如何处理呢

public class T {

public static void main(String [] args){
    float fa = 0.4f;
    float fb = 0.7f;
    
    double da = 0.4;
    double db = 0.7;
    
    System.out.println("Float to int below:"+(int)fa);
    System.out.println("Float to int above:"+(int)fb);
    System.out.println("Double to int below:"+(int)da);
    System.out.println("Double to int above:"+(int)db);
}

}

输出结果

Float to int below:0
Float to int above:0
Double to int below:0
Double to int above:0

这里可以看出不论是float还是double,在转化为int时会被截尾(小数点后面的都被截断),那么要怎么才能得到四舍五入的结果呢?这就得用到Math.round()方法了

public class T {

public static void main(String [] args){
    float fa = 0.4f;
    float fb = 0.7f;
    
    double da = 0.4;
    double db = 0.7;
    
    System.out.println("Float to int below:"+Math.round(fa));
    System.out.println("Float to int above:"+Math.round(fb));
    System.out.println("Double to int below:"+Math.round(da));
    System.out.println("Double to int above:"+Math.round(db));
}

}

输出结果

Float to int below:0
Float to int above:1
Double to int below:0
Double to int above:1

你可能感兴趣的:(类型转换截尾与舍入)