Hang BigDecimal java BigDecimal BigDecimal experience and pay attention to compare the size matters

  Hang BigDecimal java BigDecimal BigDecimal experience and pay attention to compare the size matters

 

 

First, the problems encountered

When using the BigDecimal class package java.math high precision arithmetic, using the found new BigDecimal BigDecimal object is created and BigDecimal.valueOf constructor method , actually are not equal , where easy dark green bug, and difficult to find, it records it.

 

Second, the code to reproduce

1, BigDecimal objects and new BigDecimal BigDecimal.valueOf method created

2, the output BigDecimal objects

3, comparing the address value

4, as follows:

@Test
public void test() {
	double d1 = 0.1D ;
	double d2 = 0.1D ;
	BigDecimal b1 = new BigDecimal(d1);
	BigDecimal b2 = BigDecimal.valueOf(d2);
		
	System.out.println(b1);
	System.out.println(b2);
	System.out.println(b1 == b2);
}

 

5, the output results are as follows:

0.1000000000000000055511151231257827021181583404541015625

0.1

false

 

6. Problems: b1 more than a string of floating point b2, precision exception.

 

Three, BigDecimal compare the size

1, as follows:

@Test
public void compare() {
	double d1 = 0.1D ;
	double d2 = 0.1D ;
	BigDecimal b1 = BigDecimal.valueOf(d1);
	BigDecimal b2 = BigDecimal.valueOf(d2);
		
	System.out.println(b1 == b2);
	System.out.println(b1.equals(b2));
	System.out.println(b1.compareTo(b2)); // 返回 int
}

 

2, the output results are as follows:

false

true

0

 

3, description: b1.compareTo (B2) : return int,

Is equal to 0, then b1 = b2;

Equal to 1, b1> b2;

Equals -1, b1 <b2.

 

 

IV Summary

1, new BigDecimal () the accuracy of unusual problems, please refer to the information on their own, or watching JDK source code to understand.

2, for creating BigDecimal object, use BigDecimal.valueOf (xx) method, or a new BigDecimal (String.valueOf (xx)) method. ---- reason to view the source code understanding.

3, BigDecimal comparison can compareTo method, or equals methods may be used. --- the BigDecimal method overrides the equals method but also to achieve java.lang.Comparable <BigDecimal> interface.

4, BigDecimal realize common operations (addition, subtraction, multiplication, and division) using the corresponding need for a method, the object can not be directly summed. --- Please refer to themselves JDK documentation.

5, BigDecimal also to achieve a number of reservations is not a decimal, setScale () method, to find out.

6, ......... more of their own to take a look at the pictures.

 

 

 

 

 

Published 156 original articles · won praise 159 · views 490 000 +

Guess you like

Origin blog.csdn.net/HaHa_Sir/article/details/102868793