Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace grouping separator of DecimalFormat in formatted value

I've used DecimalFormat df = new DecimalFormat("#,###.00"); to format a 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(" ",""));

But that space between 1 and 2 in 1 250.00 is not replaced. How can I fix it?

Example:

DecimalFormat df = new DecimalFormat("#,###.00");
BigDecimal example = new BigDecimal("1250");
String str = df.format(example);
System.out.println(str.replace(",",".").replace(" ",""));
like image 950
rakamakafo Avatar asked Sep 03 '15 11:09

rakamakafo


People also ask

What is number format and DecimalFormat class?

Class DecimalFormat. DecimalFormat is a concrete subclass of NumberFormat that formats decimal numbers. It has a variety of features designed to make it possible to parse and format numbers in any locale, including support for Western, Arabic, and Indic digits.

What is the use of DecimalFormat in Java?

You can use the DecimalFormat class to format decimal numbers into locale-specific strings. This class allows you to control the display of leading and trailing zeros, prefixes and suffixes, grouping (thousands) separators, and the decimal separator.

Is Java DecimalFormat thread safe?

DecimalFormat isn't thread-safe, thus we should pay special attention when sharing the same instance between threads.


1 Answers

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

You will see that the int printed is 160, which corresponds to "Non-breaking space" in ISO-8859-1.

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, ""));
like image 133
Tunaki Avatar answered Sep 23 '22 00:09

Tunaki