What would be printed to console and why?
1.
BigDecimal BigDecimalNum = new BigDecimal("0.0774");
System.out.println(BigDecimalNum.doubleValue() * 100.00);
2.
BigDecimal BigDecimalNum2 = new BigDecimal("0.0774");
System.out.println(BigDecimalNum2.multiply(new BigDecimal("100.00")));
The results on my machine are:
This doesn’t surprise me at all. In the second case we’re dealing entirely with BigDecimal, and always multiplying – there’s no reason for anything to go wrong.
In the first case you’re converting the BigDecimal to a double, so your code is effectively
The value 0.0774 can’t be exactly represented as a
double, hence the discrepancy.This has nothing to do with
BigDecimal, and everything to do withdouble. You should almost never be converting betweenBigDecimalanddoublethough – the kind of values which are appropriate for use inBigDecimalare almost always inappropriate to represent asdoublevalues.