Search code examples
javastringbigdecimalnumberformatexception

ConvertString to Big Decimal in JAVA


I am trying to store a String into a column with datatype Big Decimal.

String a = transaction.getBeneAmt();
log.info(a);
tran.setTransAmt(new BigDecimal(transaction.getBeneAmt()));
tranRepository.saveAndFlush(trangloTran); //save into database

But I get

2017-07-05 18:04:19 [http-nio-8080-exec-1] INFO  ApiController - IDR 3,000,000.00
2017-07-05 18:04:19 [http-nio-8080-exec-1] ERROR o.a.c.c.C.[.[.[.[dispatcherServlet] - Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is java.lang.NumberFormatException] with root cause
java.lang.NumberFormatException: null
    at java.math.BigDecimal.<init>(BigDecimal.java:494)
    at java.math.BigDecimal.<init>(BigDecimal.java:383)
    at java.math.BigDecimal.<init>(BigDecimal.java:806)

Solution

  • The problem here is that your String contains alphabetic characters so it won't be possible to convert it to BigDecimal, that's why you got NumberFormatException.

    You need to replace these alphabetic characters before trying to convert it:

    String a = transaction.getBeneAmt();
    log.info(a);
    tran.setTransAmt(new BigDecimal(a.replaceAll("[a-zA-Z,]", "").trim()));
    tranRepository.saveAndFlush(trangloTran);