1

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!

Community
  • 1
  • 1
Ian Knight
  • 2,356
  • 2
  • 18
  • 22
  • 1
    It's hard to do in a portable way. First, because the NumberFormat doesn't know in advance what the maximum length of the numbers it will format in the future will be. Second, because in some locales, the currency sign comes after the amount, and not before. You'll have to implement your own solution. – JB Nizet Dec 24 '12 at 16:17

2 Answers2

4

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.

Community
  • 1
  • 1
Reimeus
  • 158,255
  • 15
  • 216
  • 276
  • This looks like just the thing! For the time being, I'll just have to live with always putting the currency symbol before the value, regardless - immensely helpful, thanks :) – Ian Knight Dec 24 '12 at 20:37
0

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));
Walery Strauch
  • 6,792
  • 8
  • 50
  • 57