I'm using BigDecimal to deal with positive numbers in my app, and I want to make it truncate decimals after the 4th one. I seem to almost find what I wanted with RoundingMode.DOWN, but there's some issue when the BigDecimal is created from a double.
For example:
System.out.println("123.11119 = " + new BigDecimal("123.11119").setScale(4, RoundingMode.DOWN)); //Print 123.1111 which is exactly what I want
System.out.println("123.1111 = " + new BigDecimal("123.1111").setScale(4, RoundingMode.DOWN)); //So does this one
HOWEVER, the following prints 123.1110
which is NOT what I want at all:
System.out.println("123.1111 = " + new BigDecimal(123.1111d).setScale(4, RoundingMode.DOWN));
This is because of representation problem.
The value 123.1111d in reality can be something like 123.111091231918498.
That why it is recommended to use string constructor when you want to have exact values.