DecimalFormat变量组大小 [英] DecimalFormat variable group size

查看:169
本文介绍了DecimalFormat变量组大小的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在发布问题之前,我已经研究了这个主题,但是找不到答案。



这是我正在做的事情:

输入:一个数字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做错了吗?

编辑:

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

  DecimalFormatSymbols group = new DecimalFormatSymbols(); 
group.setGroupingSeparator('');
group.setDecimalSeparator('');
DecimalFormat idFormat = new DecimalFormat(0,000000.0,group);

从重新阅读手册,我意识到DecimalFormat没有办法打印变量(我很幸运,我只需要2 - 所以我可以使用小数部分)。但是,你将如何正确地做到这一点?在这里使用正则表达式可以吗/写我自己的函数,还是有库已经这样做了?



EDIT2:





$ b $ p $ $ c> Random random = new Random();
String.valueOf(Math.round(random.nextDouble()* 1e8))
.replaceAll((。*)(\\ { 6})(\\d)$,$ 1 $ 2 $ 3)
.replaceAll(^,0));


解决方案

我不认为您可以使用 DecimalFormat 分组分隔符。从 Javadoc


如果提供具有多个分组字符的模式,则最后一个与整数结束之间的间隔是所使用的间隔。所以#,##,###,####==######,####==##,####,####。



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

解决方案

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变量组大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆