Look at the running result of the following piece of code:
public class TestDouble { public static void main(String[] args) { double d =538.8; System.out.println(d*100); }
The output result is surprisingly not 53880, but 53879.99999999999
Solution 1 :
538.8*100 Replace with *10*10 to get the result we want
538.8*10000 Replace with 100*100.
Solution 2:
public class TestDouble { public static void main(String[] args) { double d =538.8; BigDecimal a1 = new BigDecimal(Double.toString(d)); BigDecimal b1 = new BigDecimal(Double.toString(100)); BigDecimal result = a1.multiply(b1);// 相乘结果 System.out.println(result); BigDecimal one = new BigDecimal("1"); double a = result.divide(one,2,BigDecimal.ROUND_HALF_UP).doubleValue();//保留1位数 System.out.println(a); } }
The above article briefly discusses the small problem of deviation in the result of Java double multiplication, which is all the content shared by the editor. I hope it can To give you a reference, I also hope that everyone will support the PHP Chinese website.
For more articles on the small deviation of the result of Java double multiplication, please pay attention to the PHP Chinese website!