Java类型转换之截尾和舍入

Java类型转换之截尾和舍入

窄化转换:将能容纳更多信息的数据类型转换成无法容纳那么多信息的类型

扩展转换:新类型肯定能容纳原来类型的信息

窄化转换必须显式地进行类型转换,可能面临信息丢失的危险

扩展转换不必显式地进行类型转换,不会造成任何信息的丢失

1、截尾

 1 public class CastingNumbers {
 2     public static void main(String[] args) {
 3         double above=0.7,below=0.3;
 4         float fabove=0.7f,fbelow=0.3f;
 5         System.out.println("(int)above= "+(int)above);
 6         System.out.println("(int)below= "+(int)below);
 7         System.out.println("(int)fabove= "+(int)fabove);
 8         System.out.println("(int)fbelow= "+(int)fbelow);
 9     }
10 }
11 12 /**
13  * Output:
14  * (int)above= 0
15  * (int)below= 0
16  * (int)fabove= 0
17  * (int)fbelow= 0
18  */

 

float或double转型为整型时,总是对该数字执行截尾。

2、舍入

如果想要得到舍入的结果,就需要使用java.lang.Math中的round()方法。

 

 1 public class RoundingNumbers {
 2     public static void main(String[] args) {
 3         double above=0.7,below=0.3;
 4         float fabove=0.7f,fbelow=0.3f;
 5         System.out.println("Math.round(above)= "+Math.round(above));
 6         System.out.println("Math.round(below)= "+Math.round(below));
 7         System.out.println("Math.round(fabove)= "+Math.round(fabove));
 8         System.out.println("Math.round(fbelow)= "+Math.round(fbelow));
 9     }
10 }
11 12 /**
13  * Output:
14  * Math.round(above)= 1
15  * Math.round(below)= 0
16  * Math.round(fabove)= 1
17  * Math.round(fbelow)= 0
18  */

 

 

 

posted @ 2021-05-19 16:26  sumAll  阅读(130)  评论(0编辑  收藏  举报