java是一种强类型语言,意味着必须为每一个变量生命一种类型。 java中,一共有8种基本类型,其中4种整形(short,int,long,byte),2种浮点型(float,double),1种用于表示Unicode编码字符单元的字符类型char和1种用于表示真值的boolean类型。在本文中我们来讨论一下这两个浮点类型。
float和double基本介绍
浮点类型用来表示有小数部分的数值。在java中存在两种浮点类型,float和double。
类型 | 存储需求 | 取值范围 |
---|---|---|
float | 4 byte | 大约±3.40282347E+38F(有效位数6~7位) |
double | 8 byte | 大约±1.79769313486231570E+308(有效位数15位) |
double表示这种类型的数值精度为float类型的两倍,所以double一般也成为双精度浮点型。很多情况下,float类型的精度难以满足需求。例如绝大多数应用程序都采用double类型。但是float也不是一无是处,如果对浮点数速度有要求,但是精度是在容许范围内,就可以用float啦。
声明类型
float a=100f;//浮点类型,f和F都行
double b=100;//没有f都浮点数,默认为double类型
double c=100D;//要是喜欢加个D也行
浮点数精度引起的问题
案例1
public class Main {
public static void main(String[] args) {
// write your code here
double db=100d;
int a=100;
System.out.println(a==db);
}
}
结果
true
Process finished with exit code 0
案例2
public class Main {
public static void main(String[] args) {
// write your code here
float a=123456788f;
float b=a+1;
System.out.println(a==b);
}
}
结果
true
Process finished with exit code 0
这就是精度损失的体现了
案例3
public class Main {
public static void main(String[] args) {
// write your code here
float a=0.1f;
double b=1.0/10;
System.out.println(a==b);
}
}
结果
false
Process finished with exit code 0
可见浮点数的精度损失。