javastringbigdecimal

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


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)

Solution

  • 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