Search code examples
javacurrencynumber-formattingformatter

Float values which ends with '0' cant be denoted by two decimal points


I do a number formatting to indicate currency values as follows :

 private static DecimalFormat decimalFormat = new DecimalFormat("0.00");

 List<String> paidAmounts = new ArrayList<>();

  for (Invoice invoice : invoices) {
    paidAmounts.add(String.valueOf
    ("$"+Formatter.currencyDecimalFormat(invoice.getAmount())));
   }

   public static Float currencyDecimalFormat(int value) {
    return Float.valueOf(decimalFormat.format((float) value / 100));
}

Invoice class :

    private int amount;

    public int getAmount() {
    return amount;
  }

But the values which ends with '0' are not formatted to the desirable format.

$18.5
$16.8
$105.59

How to make this correct?


Solution

  • Your Float.valueOf is reformatting the float to remove the trailing 0 because a float cannot hold a trailing 0. The String that .format returns can. If you try printing out:

    decimalFormat.format((float) value / 100)

    The float numbers will print correctly. Remove this call to .valueOf and return a String from currencyDecimalFormatinstead:

    public static String currencyDecimalFormat(int value) {
        return decimalFormat.format((float) value / 100);
    }