How can I parse a String to BigDecimal?

BenMansourNizar picture BenMansourNizar · Aug 14, 2013 · Viewed 217.7k times · Source

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.

Answer

René Link picture René Link · Aug 14, 2013

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