问题描述
在发布问题之前,我已经研究了这个主题,但是找不到答案。
这是我正在做的事情:
输入:一个数字7到8个十进制的小数位(无分数)。
输出:X XXXXXX X
示例:1234567 => 0 123456 7
什么是我尝试过:
$ p $ DecimalFormatSymbols group = new DecimalFormatSymbols();
group.setGroupingSeparator('');
DecimalFormat idFormat = new DecimalFormat(0,000000,0,group);
但是这样打印的内容类似于0 1 2 3 4 5 6 7做错了吗?
编辑: 我可以打印我需要的东西,如果我这样做: 从重新阅读手册,我意识到DecimalFormat没有办法打印变量(我很幸运,我只需要2 - 所以我可以使用小数部分)。但是,你将如何正确地做到这一点?在这里使用正则表达式可以吗/写我自己的函数,还是有库已经这样做了? EDIT2: 我不认为您可以使用 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: 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: 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 :) I don't think you can use the 这篇关于DecimalFormat变量组大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!
DecimalFormatSymbols group = new DecimalFormatSymbols();
group.setGroupingSeparator('');
group.setDecimalSeparator('');
DecimalFormat idFormat = new DecimalFormat(0,000000.0,group);
$ b $ p $ $ c> Random random = new Random();
String.valueOf(Math.round(random.nextDouble()* 1e8))
.replaceAll((。*)(\\ { 6})(\\d)$,$ 1 $ 2 $ 3)
.replaceAll(^,0));
DecimalFormat
分组分隔符。从:DecimalFormatSymbols group = new DecimalFormatSymbols();
group.setGroupingSeparator(' ');
DecimalFormat idFormat = new DecimalFormat("0,000000,0", group);
DecimalFormatSymbols group = new DecimalFormatSymbols();
group.setGroupingSeparator(' ');
group.setDecimalSeparator(' ');
DecimalFormat idFormat = new DecimalFormat("0,000000.0", group);
Random random = new Random();
System.out.println(
String.valueOf(Math.round(random.nextDouble() * 1e8))
.replaceAll("(.*)(\\d{6})(\\d)$", "$1 $2 $3")
.replaceAll("^ ", "0 "));
DecimalFormat
grouping separator for this. From the Javadoc: