On the backend I'm storing money values in a Money class which wraps a BigDecimal and sets rounding to be always Half Even with scale 8. All basic operations work fine and behave as expected. But I need to show those values to the user with scale of 2, and that's bringing me rounding errors.
For example, I have these values in the backend:
a = 109.11432
b = 9015.57069
c = 9124.68501
Each one of them is formatted to the pt-BR locale:
NumberFormat nf = NumberFormat.getInstance();
nf.setCurrency(Currency.getInstance(new Locale("pt","BR")));
nf.setMinimumFractionDigits(2);
nf.setMaximumFractionDigits(2);
String n = nf.format(valor);
return n;
And then I have
a = 109,11
b = 9.015,57
c = 9.124,69
And that's ok, at first. But c should be a + b. With the real values, this is guaranteed, but the rounding gives me a 0.01 error.
What's the proper way to handle this situation?