Squero27
Squero27

Reputation: 21

NumberFormatException when parsing a String to BigDecimal

My Code is :

String sql="insert into L_EC(AMOUNT)values(?)";

    pst=con.prepareStatement(sql);


   for(int i=0;i<dtm.getRowCount();i++){
     BigDecimal nbr= parsing(dtm.getValueAt(i, 1).toString());
     prst.setBigDecimal(1, nbr);
     prst.addBatch();
}
prst.executeBatch();

info: Column is of type Currency

private static BigDecimal parsing(String str) {
    String normalized="";
    if(str==null){
       normalized="0";
    }else{
     normalized = str.replaceAll("\\s", "").replace(',', '.');
    }
    return new BigDecimal(normalized);

problem is that when a cell from table contain NULL ,I get this message:

Exception in thread "AWT-EventQueue-0" java.lang.NumberFormatException
    at java.math.BigDecimal.<init>(BigDecimal.java:545)
    at java.math.BigDecimal.<init>(BigDecimal.java:739)
    at Vista.TCRCG.parse(TCRCG.java:130)

I think that the problem is on parsing method when the parser find a cell without a any text or value.

Upvotes: 0

Views: 8701

Answers (1)

Gord Thompson
Gord Thompson

Reputation: 123799

Your parsing method will throw that exception if str is an empty string ("") or a space (" "). You may need to do some extra checking, e.g.,

if (str == null || str.trim().length() == 0) {
    normalized = "0";

Upvotes: 1

Related Questions