sky
sky

Reputation: 447

DecimalFormat Not Giving Result as per Half_Even Rounding

I am trying to round to 1-decimal place. Below is the code snippet.

DecimalFormat decimalFormat = new DecimalFormat("#0.#");
String formattedNumber = decimalFormat.format(4.65d);
System.out.println(formattedNumber);

Output
4.7

As per DecimalFormat javadoc, its default rounding is HALF_EVEN. By this rule, 4.65 should have been rounded to 4.6. But, it is giving output as 4.7. Please help me understand this behavior.

Upvotes: 1

Views: 238

Answers (2)

DimaSan
DimaSan

Reputation: 12694

In addition to Peter's Lawrey answer you could try to pass to decimalFormat.format() method BigDecimal(String val) to ensure passing the exact value:

String formattedNumber = decimalFormat.format(new BigDecimal("4.65"));
System.out.println(formattedNumber);

You will get an output of 4.6.

Upvotes: 1

Peter Lawrey
Peter Lawrey

Reputation: 533570

A double has a small representation error for many decimal values, this included 4.65 which is actually slightly higher than it appears.

System.out.println(new BigDecimal(4.65));

prints

4.6500000000000003552713678800500929355621337890625

Upvotes: 3

Related Questions