DecimalFormat variable group size

2019-01-15 21:57发布

问题:

I've researched the subject somewhat before posting the question, but I couldn't find the answer.

Here is what I'm trying to do:

input: a number 7-8 decimal spaces long (no fractions).

output: "X XXXXXX X" where X is a digit, must be present.

example: 1234567 => 0 123456 7

What I tried:

DecimalFormatSymbols group = new DecimalFormatSymbols();  
group.setGroupingSeparator(' '); 
DecimalFormat idFormat = new DecimalFormat("0,000000,0", group);

But this prints something like "0 1 2 3 4 5 6 7" instead :S What am I doing wrong?

EDIT:

I can print what I need if I do this:

DecimalFormatSymbols group = new DecimalFormatSymbols();  
group.setGroupingSeparator(' ');
group.setDecimalSeparator(' ');
DecimalFormat idFormat = new DecimalFormat("0,000000.0", group);

And from re-reading the manual, I realized that DecimalFormat doesn't have a way to print variable length groups (I'm lucky I only need 2 - so I can use fraction part). But how would you do this "properly"? Would it be OK to use regular expression here / write my own function, or are there libraries that do this already?

EDIT2:

Just for kicks, below is the regex-based way of doing it :)

Random random = new Random();
System.out.println(
      String.valueOf(Math.round(random.nextDouble() * 1e8))
      .replaceAll("(.*)(\\d{6})(\\d)$", "$1 $2 $3")
      .replaceAll("^ ", "0 "));

回答1:

I don't think you can use the DecimalFormat grouping separator for this. From the Javadoc:

If you supply a pattern with multiple grouping characters, the interval between the last one and the end of the integer is the one that is used. So "#,##,###,####" == "######,####" == "##,####,####".



回答2:

You can use ICU4J library's com.ibm.icu.text.DecimalFormat class for this same purpose. It supports variable length group size. For your particular case:

com.ibm.icu.text.DecimalFormatSymbols dfs = new com.ibm.icu.text.DecimalFormatSymbols();
dfs.setGroupingSeparator(' ');
com.ibm.icu.text.DecimalFormat df = new com.ibm.icu.text.DecimalFormat("0,000000,0", dfs); 

This should print '0 123456 7' for a number like '1234567'.