The pitfalls of Java BigDecimal

1. The pit of the constructor

public void constructTest(){

   BigDecimal value1 =new BigDecimal(10.511);
   System.out.println("value1: " + value1);
   BigDecimal value2 = new BigDecimal("10.511");
   System.out.println("value2: " + value2);

}

According to our expectation, the output of value1 should be 10.511, but the actual value is not like this, as follows:

value1: 10.510999999999999232613845379091799259185791015625
value2: 10.511

When we use double data as a parameter, the constructed BigDecimal object value1 does not guarantee the accuracy of the data. 
When constructing an object with String as a parameter, the accuracy of the data is guaranteed.

 

2. BigDecimal immutability pit

BigDecimal has the same object immutable line as String, once assigned, it will not change.

public void immutableTest() {

   BigDecimal count = new BigDecimal("1.3");
   count.add( new BigDecimal("9.2"));
   System.out.println("count:" + count);

}
count:1.3

Executing the code will find that count is not the expected 10.5, or the initial assignment 1.3 
BigDecimal must save the result when doing the operation.

 

 

 

Guess you like

Origin blog.csdn.net/johnt25/article/details/86743478