This question already has an answer here:
- Safe String to BigDecimal conversion 9 answers
I have this String: 10,692,467,440,017.120 (it's an amount).
I want to parse it to a BigDecimal. The problem is that I have tried both DecimalFormat and NumbeFormat in vain. Any help?
BigDecimal offers a string constructor. You'll need to strip all commas from the number, via via an regex or
String filteredString=inString.replaceAll(",","")
.You then simply call
BigDecimal myBigD=new BigDecimal(filteredString);
You can also create a
NumberFormat
and callsetParseBigDecimal(true)
. Thenparse(
will give you a BigDecimal without worrying about manually formatting.Try the correct constructor http://docs.oracle.com/javase/7/docs/api/java/math/BigDecimal.html#BigDecimal(java.lang.String)
You can directly instanciate the BigDecimal with the String ;)
Example:
Try this
Try this
If you are building an application with I18N support you should use
DecimalFormatSymbols(Locale)
Also keep in mind that
decimalFormat.parse
can throw aParseException
so you need to handle it (with try/catch) or throw it and let another part of your program handle it