How do I convert a string number value with a dollar sign to BigDecimal in java?

JNPW picture JNPW · Jan 26, 2012 · Viewed 81.2k times · Source

I have a dollar amount in a String format. For example: String salePrice = $348.00.

However, I want to convert this String value to a BigDecimal value, but it has a dollar sign in the string. I tried the code below but it isn't working.

BigDecimal sPrice = new BigDecimal(salePrice);

I ended up getting this exception below:

java.lang.NumberFormatException
    at java.math.BigDecimal.<init>(Unknown Source)
    at java.math.BigDecimal.<init>(Unknown Source)

Answer

RanRag picture RanRag · Jan 26, 2012

The BigDecimal Constructor take a valid numerical string.

The String representation consists of an optional sign, '+' ('\u002B') or '-' ('\u002D'), followed by a sequence of zero or more decimal digits ("the integer"), optionally followed by a fraction, optionally followed by an exponent.

String salePrice = "$348.00";
String price = salePrice.replace("$","");
BigDecimal sPrice = new BigDecimal(price);
System.out.println(sPrice);

Output = 348.00

You can also look at NumberFormat class. Using this class you can set your corresponding Locale.

String salePrice = "$123.45";
Locale locale = Locale.US;
Number number = NumberFormat.getCurrencyInstance(locale).parse(salePrice);
System.out.println(number);

Output = 123.45