DecimalFormat 可变组大小

DecimalFormat variable group size(DecimalFormat 可变组大小)
本文介绍了DecimalFormat 可变组大小的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

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

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

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

How to send data to COM PORT using JAVA?(如何使用 JAVA 向 COM PORT 发送数据?)
How to make a report page direction to change to quot;rtlquot;?(如何使报表页面方向更改为“rtl?)
Use cyrillic .properties file in eclipse project(在 Eclipse 项目中使用西里尔文 .properties 文件)
Is there any way to detect an RTL language in Java?(有没有办法在 Java 中检测 RTL 语言?)
How to load resource bundle messages from DB in Java?(如何在 Java 中从 DB 加载资源包消息?)
How do I change the default locale settings in Java to make them consistent?(如何更改 Java 中的默认语言环境设置以使其保持一致?)