Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I parse a String to BigDecimal? [duplicate]

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.

like image 933
BenMansourNizar Avatar asked Aug 14 '13 12:08

BenMansourNizar


People also ask

Can BigDecimal be double?

The doubleValue() method of Java BigDecimal class is used to convert the BigDecimal value into a double type. If BigDecimal has very big value represented as a double, it will be converted to Double. NEGATIVE_INFINITY or Double. POSITIVE_INFINITY as appropriate.


1 Answers

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

like image 98
René Link Avatar answered Oct 06 '22 00:10

René Link