How can I parse a String to BigDecimal?

JavaStringParsingBigdecimalDecimalformat

Java Problem Overview


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.

Java Solutions


Solution 1 - Java

Try this

// Create a DecimalFormat that fits your requirements
DecimalFormatSymbols symbols = new DecimalFormatSymbols();
symbols.setGroupingSeparator(',');
symbols.setDecimalSeparator('.');
String pattern = "#,##0.0#";
DecimalFormat decimalFormat = new DecimalFormat(pattern, symbols);
decimalFormat.setParseBigDecimal(true);

// parse the string
BigDecimal bigDecimal = (BigDecimal) decimalFormat.parse("10,692,467,440,017.120");
System.out.println(bigDecimal);

If you are building an application with I18N support you should use DecimalFormatSymbols(Locale)

Also keep in mind that decimalFormat.parse can throw a ParseException so you need to handle it (with try/catch) or throw it and let another part of your program handle it

Solution 2 - Java

Try this

 String str="10,692,467,440,017.120".replaceAll(",","");
 BigDecimal bd=new BigDecimal(str);

Solution 3 - Java

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:

BigDecimal bigDecimalValue= new BigDecimal("0.5");

Solution 4 - Java

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 call setParseBigDecimal(true). Then parse( will give you a BigDecimal without worrying about manually formatting.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionBenMansourNizarView Question on Stackoverflow
Solution 1 - JavaRené LinkView Answer on Stackoverflow
Solution 2 - JavaRuchira Gayan RanaweeraView Answer on Stackoverflow
Solution 3 - JavaRene M.View Answer on Stackoverflow
Solution 4 - JavananofaradView Answer on Stackoverflow