Search code examples
javanumber-formattingdecimalformat

How to change the grouping separator (thousands) of DecimalFormat from comma/point to quote using patterns?


I have this piece of code where I try to replace the thousands separator (.) for quote (') with this pattern: ###'###,##

import java.text.*;

  public class NumberFormatTests
  {
    public static void main (String[] args)
    {
      double amount = 100100.543;
      NumberFormat nf = new DecimalFormat("###'###.##");
      System.out.println( "amount with    formatting: " + nf.format(amount) );
    }
  }

but I get this error:

Exception in thread "main" java.lang.IllegalArgumentException: Malformed pattern "###'###.##" at java.text.DecimalFormat.applyPattern(DecimalFormat.java:3411) at java.text.DecimalFormat.(DecimalFormat.java:436) at NumberFormatTests.main(NumberFormatTests.java:8)

I know it can be changed programatically by using DecimalFormatSymbols like this:

import java.text.*;
import java.util.Locale;

  public class NumberFormatTests
  {
    public static void main (String[] args)
    {
      double amount = 100100.543;

      Locale currentLocale = new Locale("de", "DE");
      DecimalFormatSymbols unusualSymbols = new DecimalFormatSymbols(currentLocale);
      unusualSymbols.setGroupingSeparator('\'');

      NumberFormat nf = new DecimalFormat("###,###.##", unusualSymbols);
      System.out.println( "amount with    formatting: " + nf.format(amount) );
    }
  }

but I need to find a way to do it within the pattern, something like "###'###.##". I already tried "###''###.##" but the quote is added as suffix.

Is there any way to replace the thousands separator already within the pattern and not programatically?


Solution

  • Can you use a subclass of DecimalFormat instead? You could analyze the pattern in the subclass and extract the unusual grouping separator from the pattern. On a call of the subclass's format method, you can use this grouping separator with the original DecimalFormat as shown in your own example code. This is the result that is returned by the format method of the subclass.