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(" ",""));
You can set grouping separator (e.g. thousand separator) character in your pattern by using
DecimalFormatSymbols
. It looks that in your locale it is non-breaking space so try to set it to normal space likeNow your formatter will use simple space so you will be able to replace it with your code
Output:
1250.00
.You can use the
parse
method from yourDecimalFormat
object.Take a look at the selected answer in this SO question.
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: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:
For a more general solution, not depending on the current locale, we could retrieve the grouping separator and use that directly:
In your format
the symbol
,
is meant for grouping separator. After removing the symbol,
from your format you get the output 1250.00 (without grouping separator in your case space).There is alternative (2nd) solution and it works without altering your format "#,###.00". Use .setGroupingSize(0) from DecimalFormat: