Question

Am having an issue with formatting currencies in Java. I am trying to format a number to be printed as currency, with all the decimal points aligned:

£  1.23
£ 12.34
£123.45

Calling NumberFormat.getCurrencyInstance().format(n) returns a formatted string, but all the numbers are left-aligned, producing output like this:

£1.23
£12.34
£123.45

Ugly. I have read this post which presents a solution using a DecimalFormat, and as a stopgap I'm formatting my number using a DecimalFormat and prepending the currency symbol later, but I was wondering if anyone was aware of a neater way of accomplishing the same thing?

Hope that's all clear, thanks in advance for your help!

Was it helpful?

Solution

You could do:

String currencySymbol = Currency.getInstance(Locale.getDefault()).getSymbol();
System.out.printf("%s%8.2f\n", currencySymbol, 1.23);
System.out.printf("%s%8.2f\n", currencySymbol, 12.34);
System.out.printf("%s%8.2f\n", currencySymbol, 123.45);

Note: this will only work for currencies whose symbols appear before the amount.

Also be alert to the fact that doubles are not suitable for representing currency.

OTHER TIPS

Try this:

    final NumberFormat nf = NumberFormat.getCurrencyInstance();

    nf.setMinimumIntegerDigits(3);

    System.out.println(nf.format(1.23));
    System.out.println(nf.format(12.34));
    System.out.println(nf.format(123.45));
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top