DecimalFormat variable group size

 ̄綄美尐妖づ 提交于 2019-12-17 17:22:32

问题


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'.



来源:https://stackoverflow.com/questions/10229716/decimalformat-variable-group-size

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!