Matters needing attention when BigDecimal performs multiplication and division operations

Dolphin Elf : https://mgo.whhtjl.com

1. Do multiplication (precision problem)

Youke GO business requirements: After the card user has successfully paid, 30% of the card fee will be rewarded to the direct promoter, with 2 decimal places, and never increase the number before the discarded (ie truncated) decimal.

package test;
import java.math.BigDecimal;
import java.math.RoundingMode;
public class Test {
	public static void main(String[] args) {
		String money="0.1";//卡费
		BigDecimal reallyPayMoney=new BigDecimal(money);
		System.out.println("结果:"+reallyPayMoney.multiply(new BigDecimal(0.3)).setScale(2, RoundingMode.DOWN));
	}
}

Running the above code shows the results as follows:

Huh, isn't 0.1*0.3 equal to 0.03? How could it be 0.02?

Later, it was discovered that when Decimal was doing multiplication, it would convert 0.3 to float, which caused the value to change due to insufficient precision, and thus failed to calculate the ideal value.

The solution is to set the parameter to String type during initialization

Run again after modifying the code, and the result is as follows:

2. Divide (infinite loop decimal appears)

System.out.println(BigDecimal.ONE.divide(new BigDecimal("3")));

Run an error, as shown below:

The solution is to set the precision during operation, modify the code and run, the result is as follows:

OK

 

Guess you like

Origin blog.csdn.net/qq_35393693/article/details/108528582