DecimalFormat 可变组大小

2022-01-12 00:00:00 formatting java

在发布问题之前,我已经对该主题进行了一些研究,但找不到答案.

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

这是我想要做的:

输入:一个长 7-8 个小数位的数字(无分数).

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

输出:X XXXXXX X",其中 X 是一个数字,必须存在.

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

示例:1234567 => 0 123456 7

example: 1234567 => 0 123456 7

我尝试了什么:

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

但这会打印出类似0 1 2 3 4 5 6 7"的内容:S 我做错了什么?

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

如果我这样做,我可以打印我需要的东西:

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);

通过重新阅读手册,我意识到 DecimalFormat 没有办法打印可变长度组(幸运的是我只需要 2 个 - 所以我可以使用小数部分).但是你将如何正确"地做到这一点?是否可以在这里使用正则表达式/编写我自己的函数,或者是否有库已经这样做了?

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?

只是为了好玩,下面是基于正则表达式的方法:)

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 "));

推荐答案

我认为您不能为此使用 DecimalFormat 分组分隔符.来自 Javadoc:

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

相关文章