Basics of JAVA--The method of judging whether the DOUBLE types are equal

In Java, the double equal sign can be used to compare the size of int type data , but the double equal sign cannot be used to compare the size of the double type . If used, the result will always be unequal, even if the precision of the two is the same. . Two methods of comparing double data for equality are described below.

The first method: convert to a string

        If the string precision of the two double data to be compared is equal, you can convert the data into a string and use the equals method of the string to indirectly compare whether the two double data are equal.

Note: This method is only suitable for comparing data with the same precision, and it is only used to compare whether they are equal, and cannot be used to judge the size.

Float.toString(453.2348f).equals(Float.toString(0.342f))
 
Double.toString(0.8456d).equals(Float.toString(0.242f))

 

The second method: use the DOUBLE.DOUBLETOLONGBITS() method provided by SUN

This method can convert double into long data , so that double can judge whether the size and equality are equal according to the method of long (<, >, ==).

Double.doubleToLongBits(0.01) == Double.doubleToLongBits(0.01) 
Double.doubleToLongBits(0.02) > Double.doubleToLongBits(0.01) 
Double.doubleToLongBits(0.02) < Double.doubleToLongBits(0.01)

The third method:

For the double type, such as double d1=0.0000001, double d2=0d When judging whether two data d1 and d2 are equal, it is generally not used directly

if(d1==d2)

fourth way

double a = 0.001; 
double b = 0.0011; 
BigDecimal data1 = new BigDecimal(a); 
BigDecimal data2 = new BigDecimal(b); 
data1.compareTo(data2) 
非整型数,运算由于精度问题,可能会有误差,建议使用BigDecimal类型!

 

--------------------------------------No text below---------- --------------------------------------------------

Note: For study only, record questions and reference, encourage each other!

Guess you like

Origin blog.csdn.net/qq_39715000/article/details/126197433