如果將一個浮點數(shù)轉(zhuǎn)化為整數(shù)的話礼预,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);
}
}
輸出結(jié)果
Float to int below:0
Float to int above:0
Double to int below:0
Double to int above:0
這里可以看出不論是float還是double,在轉(zhuǎn)化為int時會被截尾(小數(shù)點后面的都被截斷)所计,那么要怎么才能得到四舍五入的結(jié)果呢运吓?這就得用到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));
}
}
輸出結(jié)果
Float to int below:0
Float to int above:1
Double to int below:0
Double to int above:1