I am using DecimalFormat to round a value(in Double type) to 2 decimal places
var decimalFormat = new DecimalFormat("0.0");
decimalFormat.setRoundingMode(RoundingMode.HALF_UP);
decimalFormat.setMaximumFractionDigits(2);
return decimalFormat.format(value);
When value = 50.275 => result is 50.27 As expected, the result should be 50.28 I have tried using RoundingMode.HALF_EVEN as well but it didn't work either.
50.275
cannot be represented exactly and the actual floating point value is something like 50.274999
. Thus it is rounded down.
If you have 50.275
as a String
, you can create a BigDecimal
out of it and format that.
new BigDecimal("50.275").setScale(2, RoundingMode.HALF_UP).toPlainString();
// 50.28