On the small problem of the deviation of Java double multiplication
- 2020-06-01 09:50:53
- OfStack
Take a look at the results of the following 1 piece of code:
public class TestDouble {
public static void main(String[] args) {
double d =538.8;
System.out.println(d*100);
}
The output was surprisingly not 53880 but 53879.99999999999
Solution 1:
538.8*100 and replace it with *10*10 to get what we want
538.8 times 10000 is replaced by 100 times 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);// Multiply the result
System.out.println(result);
BigDecimal one = new BigDecimal("1");
double a = result.divide(one,2,BigDecimal.ROUND_HALF_UP).doubleValue();// keep 1 digits
System.out.println(a);
}
}