Not much to say, let’s record it first.
BigDecimal coins = new BigDecimal(“0”);
BigDecimal one = new BigDecimal(“1”);
BigDecimal two = new BigDecimal(“2”);
coins = coins.add( two ); //coins plus 2
System.out.println( coins.doubleValue()); //output is 2.0
coins = coins.subtract( one ); //coins minus 1
System.out.println( coins.doubleValue()); //The output is 1.0
coins = coins.multiply( two ); //coins are multiplied by 2
System.out.println( coins.doubleValue()); //The output is 2.0
int i = coins .compareTo(BigDecimal.ZERO) ; //Judge whether coins is greater than 0
int k = coins .compareTo( one ) ;//If i = 0, it means they are equal; if i 0 means coins > one
coins = coins.setScale(2,BigDecimal.ROUND_HALF_UP) //Save two decimal places
Division is trickier:
When the bigdecimal type does division, there is no problem when the result is an integer or a finite decimal. If the result cannot be divisible, an error will be reported for an infinite decimal
Error code:
Bigdecimal bd = num1.divide(c).setScale(6,ROUND_HALF_UP);
Error message: Non-terminating decimal expansion; no exact representable decimal result”
Error translation: infinite decimal expansion; no exact decimal result.
Reason for error: temporarily unknown
Code improvements:
BigDecimal bd = num.divide(c,6,ROUND_HALF_UP);