63

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.

1
  • Show us what you have tried. We'll help
    – Tala
    Commented Aug 14, 2013 at 12:33

4 Answers 4

83

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

1
  • If the grouping and decimal separator are switched the above code will not work. It will work if DecimalFormat is initialized as it follows DecimalFormat res = new DecimalFormat(); res.setDecimalFormatSymbols(symbols); res.applyLocalizedPattern(formatter); Commented Jan 18, 2021 at 9:22
27

Try this

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

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");
2
  • BigDecimal can not parse the example string.
    – Tarynn
    Commented Sep 8, 2016 at 14:42
  • It will fail for the string value: 1,000 commas are not taking care in construction conversion. Commented Feb 6, 2020 at 17:25
14

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.

Not the answer you're looking for? Browse other questions tagged or ask your own question.