RSS Feed for This PostCurrent Article

Java: Currency Rounding Issue

This is one of the issues raised to me recently. I have a function that round the amount to the nearest 10 cents. E.g. 0.53 is rounded down to 0.5, and 3.15 is rounded up to 3.2.

public static String formatNearestTenCent(double value) {
       DecimalFormat formatter = 
            new DecimalFormat("###.#");
       return formatter.format(value);
}

But look at the following code snippet.

System.out.println
         (PriceUtils.formatNearestTenCent(1.15));
System.out.println
         (PriceUtils.formatNearestTenCent(1.05));
        

The output is

1.2
1

1.15 is correctly rounded to 1.2 but 1.05 is wrongly rounded to 1 instead of 1.1.

I will not go into the details of the problem. Enough to say that this is due to the internal representation of the floating point value.

To resolve this problem, we have to use the BigDecimal class.

public static String formatNearestTenCent(double value)
      {
      BigDecimal amount = new 
                 BigDecimal(String.valueOf(value));
      amount = amount.setScale(1, RoundingMode.HALF_UP);
      return amount.toPlainString();
}

The output is

1.2
1.1

The output is correct now by using BigDecimal. That is the reason we need BigDecimal.

You can find a good reference here.


Trackback URL


Sorry, comments for this entry are closed at this time.