issue with DecimalFormat in java

I am facing issue in below code -

int precision = 3;

String value1 = "2.0425";

String value2 = "2.1425";

DecimalFormat dfForm = new DecimalFormat();

dfForm.setMinimumFractionDigits(precision);

dfForm.setMaximumFractionDigits(precision);

System.out.println(dfForm.format(value1));

System.out.println(dfForm.format(value2));

Output -

2.042

2.143

1st output is expected to be 2.043. Can anyone help me in this?

Jon Skeet
people
quotationmark

From the docs for DecimalFormat:

DecimalFormat provides rounding modes defined in RoundingMode for formatting. By default, it uses RoundingMode.HALF_EVEN.

It sounds like you just need:

dfForm.setRoundingMode(RoundingMode.HALF_UP);

That's after you've fixed your code to call format on actual numbers, mind you:

BigDecimal value1 = new BigDecimal("2.0425");        
BigDecimal value2 = new BigDecimal("2.1425");

If you just use double values, you'll still see 2.042, as the nearest double to 2.0425 is 2.042499999999999982236431605997495353221893310546875.

people

See more on this question at Stackoverflow