如何解决Java中浮点类型的精度问题呢?
下文笔者讲述处理java代码的精度问题,如下所示
精度问题展示
精度问题说明
在一些特殊数据类型的计算时 出现小数点位数后面很多位 这就是Java中数据类型的精度问题 -------------------------------------------------------- 那么如何解决这个精度问题呢?下文笔者将一一道来,如下所示例:
精度问题展示
public static void main(String[] args) throws Exception { float a = 1.0f - 0.9f; float b = 0.9f - 0.8f; System.out.println(a == b);//false Float c = a; Float d = b; System.out.println(c.equals(d));//false System.out.println(a);//0.100000024 System.out.println(b);//0.099999964 } public static void main(String[] args) throws Exception { double a = 1.0 - 0.9; double b = 0.9 - 0.8; System.out.println(a == b);//true Double c = a; Double d = b; System.out.println(c.equals(d));//true System.out.println(a);//0.09999999999999998 System.out.println(b);//0.09999999999999998 }
由于浮点数之间存在精度问题 当我们对基本数据类型之间比较时 不能使用 == 进行比较 其对应的包装类型,不能使用equals进行比较
java开发时,存在精度问题的数据-如何进行判断呢?
设置两个浮点数之间相减,得到一个误差值 然后误差值在指定范围内,我们则认为这两个浮点数相等例
public static void main(String[] args) throws Exception { float a = 1.0f - 0.9f; float b = 0.9f - 0.8f; float diff = 1e-6f; //absolute value System.out.println(Math.abs(a - b) < diff);//true } //方式2:使用BigDecimal定义数据类型,然后进行浮点数之间的比较 public static void main(String[] args) throws Exception { BigDecimal a = BigDecimal.valueOf(1.0); BigDecimal b = BigDecimal.valueOf(0.9); BigDecimal c = BigDecimal.valueOf(0.8); BigDecimal x = a.subtract(b); BigDecimal y = b.subtract(c); System.out.println(x.equals(y));//true System.out.println(x);//0.1 System.out.println(y);//0.1 }
版权声明
本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。