Replace DecimalFormat grouping delimiter in formatted value

I used DecimalFormat df = new DecimalFormat("#,###.00");for formatting BigDecimal.

Now I want to use this formatted value (for example, "1,250.00") to create new BigDecimal. I tried this:

BigDecimal result = new BigDecimal(model.getValue().replace(",",".").replace(" ",""));

But that spacebetween 1 and 2 in 1 250.00 is not replaced. How can i fix this?

Example:

DecimalFormat df = new DecimalFormat("#,###.00");
BigDecimal example = new BigDecimal("1250");
String str = df.format(example);
System.out.println(str.replace(",",".").replace(" ",""));
+4
source share
4 answers

DecimalFormatJavadoc indicates that the character ,is a grouping delimiter. By default, for your locale, this separator is not space, but inextricable. This can be shown with the following code:

DecimalFormatSymbols symbols = new DecimalFormatSymbols(Locale.forLanguageTag("ru-RU"));
System.out.println((int) symbols.getGroupingSeparator());

, int 160, "Non-break space" ISO-8859-1.

, Unicode :

DecimalFormat df = new DecimalFormat("#,###.00");
String str = df.format(new BigDecimal("1250"));
System.out.println(str.replace(",", ".").replace("\u00A0", ""));

, , :

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, ""));
+3

parse DecimalFormat.

df.setParseBigDecimal(true);    
BigDecimal bigDecimal = (BigDecimal) df.parse(model.getValue());

SO.

+2

new DecimalFormat("#,###.00"); 

, . , 1250.00 ( ).

DecimalFormat df = new DecimalFormat("####.00");
BigDecimal example = new BigDecimal("1250");
String str = df.format(example);
System.out.println(str.replace(",",".").replace(" ",""));

: 1250,00

(2nd), "# , ###. 00". . SetGroupingSize (0) DecimalFormat:

DecimalFormat df = new DecimalFormat("#,###.00");
df.setGroupingSize(0);
BigDecimal example = new BigDecimal("1250");
String str = df.format(example);
System.out.println(str);

: 1250,00

+2

(, ) DecimalFormatSymbols. , , ,

DecimalFormatSymbols symbols = new DecimalFormatSymbols(Locale.getDefault());
symbols.setGroupingSeparator(' ');//simple space

DecimalFormat df = new DecimalFormat("#,###.00", symbols);

BigDecimal example = new BigDecimal("1250");
String str = df.format(example);

Your formatter will now use simple space so that you can replace it with your code.

System.out.println(str.replace(",", ".").replaceAll(" ", ""));

Output: 1250.00.

+2
source

Source: https://habr.com/ru/post/1605722/


All Articles