-1

I need to take a String that contains a double (something like 14562.34) and format it so that it looks like $000,000,00#.##-. What I mean by that is the $ will be all the way to the left, the 0s above won't show up if a number is not there but I do want the spacing to be there. The #s will be digits and I need at least 0.00 to show up if the number is zero. The '-' will show up if the number is a negative(though I believe that is something I can tack on at the end w/o the formatter). When I try doing "000,000,00#.##" for the formatter I get a malformed exception.

Would anyone have tips on doing this or on what I am doing wrong?

Here are examples:

1234.56 -> $______1,234.56

0 -> $__________0.00

1234567.89 -> $__1,234,567.89

Where the '_' represents a space still there.

Thanks.

Klassic_K
  • 55
  • 1
  • 8
  • I think this question answers what you are looking for (http://stackoverflow.com/questions/13791409/java-format-double-value-as-dollar-amount) – Pritam Banerjee Dec 22 '15 at 00:22
  • 2
    Possible duplicate of [Using BigDecimal to work with currencies](http://stackoverflow.com/questions/1359817/using-bigdecimal-to-work-with-currencies) – Abdelhak Dec 22 '15 at 00:28

2 Answers2

1
public static void main(String[] args) throws ParseException {
String data = "1234.6";
DecimalFormat df = new DecimalFormat("$0,000,000,000.00");
System.out.println( df.format(Double.parseDouble(data)));
}

Note the "00", meaning exactly two decimal places.

If you use "#.##" (# means "optional" digit), it will drop trailing zeroes - ie new DecimalFormat("#.##").format(3.0d); prints just "3", not "3.00".

Edit:-

If you want space instead of zero, you can use String.format() method to achieve this. If size of decimal is gretaer than max leading zero size, return the double parse number with dollar sign, otherwise add leading space.

Here length is the max size till space can be added, after that leading space is ignored.

public static String leadingZeros(String s, int length) {
    if (s.length() >= length) return String.format("$%4.2f",Double.valueOf(s));
    else 
        return String.format("$%" + (length-s.length()) + "s%1.2f",  " ",Double.valueOf(s));
    } 
Naruto
  • 4,221
  • 1
  • 21
  • 32
0

If you are looking for specifics on how to format currency from a number... This is the best way to ensure the proper locale and formatting for your numerical currency display.

public String getFormattedCurrencyValue(String number){

   BigDecimal num = new BigDecimal(number);
   NumberFormat nf = NumberFormat.getCurrencyInstance(locale);
   Currency currency = nf.getCurrency();

   String str = StringUtil.replace(
            nf.format(number),
            nf.getCurrency().getSymbol(locale),
            "",false).trim();

   return currency.getCurrencyCode()+str;
}
AnthonyJClink
  • 1,008
  • 2
  • 11
  • 32