用格式值替换DecimalFormat的分组分隔符 [英] Replace grouping separator of DecimalFormat in formatted value
问题描述
我已经使用DecimalFormat df = new DecimalFormat("#,###.00");
格式化BigDecimal
.
现在,我想使用该格式化值(例如为'1 250,00')来创建new BigDecimal
.我已经尝试过了:
Now, I want to use that formatted value (say it is '1 250,00') to create new BigDecimal
. I've tried this:
BigDecimal result = new BigDecimal(model.getValue().replace(",",".").replace(" ",""));
但是不会替换1 250.00中1和2之间的space
.我该如何解决?
But that space
between 1 and 2 in 1 250.00 is not replaced. How can I fix it?
示例:
DecimalFormat df = new DecimalFormat("#,###.00");
BigDecimal example = new BigDecimal("1250");
String str = df.format(example);
System.out.println(str.replace(",",".").replace(" ",""));
推荐答案
DecimalFormat
Javadoc指定符号,
是分组分隔符.默认情况下,对于您的语言环境,此分隔符不是一个空格,而是一个不间断的空格.可以通过以下代码显示:
DecimalFormat
Javadoc specifies that the symbol ,
is the grouping separator. By default, for your locale, this separator is not a space but a non-breaking space. This can be shown by the following code:
DecimalFormatSymbols symbols = new DecimalFormatSymbols(Locale.forLanguageTag("ru-RU"));
System.out.println((int) symbols.getGroupingSeparator());
您会看到打印的int
是160,它对应于非打破空间" .
You will see that the int
printed is 160, which corresponds to "Non-breaking space" in ISO-8859-1.
要删除该字符,我们可以使用其 Unicode表示形式并替换为:>
To remove that character, we can use its Unicode representation and replace that:
DecimalFormat df = new DecimalFormat("#,###.00");
String str = df.format(new BigDecimal("1250"));
System.out.println(str.replace(",", ".").replace("\u00A0", ""));
对于更通用的解决方案,不依赖于当前的语言环境,我们可以检索分组分隔符并直接使用它:
For a more general solution, not depending on the current locale, we could retrieve the grouping separator and use that directly:
DecimalFormat df = new DecimalFormat("#,###.00");
String groupingSeparator = String.valueOf(df.getDecimalFormatSymbols().getGroupingSeparator());
String str = df.format(new BigDecimal("1250"));
System.out.println(str.replace(",", ".").replace(groupingSeparator, ""));
这篇关于用格式值替换DecimalFormat的分组分隔符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!