简体   繁体   English

将字符串解析为BigDecimal时出现NumberFormatException

[英]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 信息:列的类型为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: 问题是,当表中的单元格包含NULL时,我收到此消息:

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. 我认为问题出在解析器找到没有任何文本或值的单元格时的解析方法上。

Your parsing method will throw that exception if str is an empty string ( "" ) or a space ( " " ). 如果str是一个空字符串( "" )或一个空格( " " ),则您的parsing方法将引发该异常。 You may need to do some extra checking, eg, 您可能需要做一些额外的检查,例如

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM