問題描述
在發布問題之前,我已經對該主題進行了一些研究,但找不到答案.
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 "#,##,###,####" == "######,####" == "##,####,####".
這篇關于DecimalFormat 可變組大小的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!