Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
174 views
in Technique[技术] by (71.8m points)

java - DecimalFormat variable group size

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 "));
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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 "#,##,###,####" == "######,####" == "##,####,####".


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...