For getting a String with exactly 2 digits after the "." I can do something like:
DecimalFormat df = (DecimalFormat)DecimalFormat.getInstance(Locale.US);
df.applyPattern("0.00");
df.setRoundingMode(RoundingMode.HALF_UP);
String output = df.format(value);
When I have a number such as 828.054999999702d
, it will format it to 828.05 what is so far correct, since the next digit says "4" and it will round that down to nothing.
But what if I need to preserve more digits precision, just don't want to show it?
What I quickly created is this working code:
double prettyValue = value;
prettyValue = Math.round(prettyValue * 1000000d) / 1000000d;
prettyValue = Math.round(prettyValue * 100000d) / 100000d;
prettyValue = Math.round(prettyValue * 10000d) / 10000d;
prettyValue = Math.round(prettyValue * 1000d) / 1000d;
prettyValue = Math.round(prettyValue * 100d) / 100d;
DecimalFormat df = (DecimalFormat)DecimalFormat.getInstance(Locale.US);
df.applyPattern("0.00");
df.setRoundingMode(RoundingMode.HALF_UP);
String output = df.format(prettyValue);
This will round the 6th, 5th, 4th, 3th and then the second place, NumberFormat will not have to do anything but just print the 2 remaining digits, after that there will be zeroes.
But I think there should be already an out-of-the-box rounding that I just don't see. Trying to do the same with BigDecimals leads to exactly the same issue for me.
The result I want is to get 828.054999999702
rounded to 828.06
.