简体   繁体   中英

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)

The BigDecimal Constructor take a valid numerical string.

The String representation consists of an optional sign, '+' ('\+') or '-' ('\-'), 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

首先删除美元符号($)。

The constructor requires a Number in the string, your string starts with a $ , which is not a valid number. You need to strip it out first.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM