I was struggling to get the right results with BigDecimal
for several hours.
I have the number 7.7049. I want to first round to 3 digits. I will get 7.705. Then round this more, to 2 digits. I should get 7.71.
I tried this:
BigDecimal(result).setScale(2, RoundingMode.HALF_UP) //instead of 2 can be any other number
But I get the wrong number: 7.70
.
I have tried different modes. I have also tried valueOf(result.toDouble())
and nothing works.
The problem here looks like setScale
working with only 2 last digits after .
and ignoring others.
How can I fix this?
UPDATED:
More examples:
7.7019 must be 7.70 | 7.7052 must be 7.71 | 7.7071 must be 7.71 | 7.7030 must be 7.70
You can first round the first 3 digits, and then the first two digits to get what you want.
BigDecimal a = new BigDecimal("7.7039")
.setScale(3, RoundingMode.HALF_UP)
.setScale(2, RoundingMode.HALF_UP);
Results are compatible with your test cases. I have not tested this for negative numbers, and it will probably not yield expected results for numbers with arbitrary precision.
You can consult the docs on RoundingMode and use this idea to perhaps come up with a scheme that rounds numbers in the non-standard way you want.