Home > other >  How to solve java.lang.NumberFormatException: For input string: "396.00"
How to solve java.lang.NumberFormatException: For input string: "396.00"

Time:11-26

I have made a small application in java. I want to insert supplier payment in mysql database.Now the issue is when i try to subtract total balance with total payment and enter in balance column. so it give me error like java.lang.NumberFormatException: For input string: "396.00". So how can I solve it

if(jCheckBox1.isSelected())
{
    String bx="Insert into supplierpaymenttable(Supplier_ID,SupplierInvoice_ID,User_ID,InvoiceNo,TotalAmount,PaymentAmount,RemainingBalance) VALUES (?,?,?,?,?,?,?)";
      
    PreparedStatement pay=conn.prepareStatement(bx);
    int k=Integer.parseInt(jTextField5.getText());
    int cx=k-k;
                
    pay.setString(1,String.valueOf(supplier));
    pay.setString(2,String.valueOf(det));
    pay.setString(3,"1");
    pay.setString(4, String.valueOf(invoie));
    pay.setInt(5, Integer.valueOf(jTextField5.getText()));
    pay.setInt(6, Integer.valueOf(jTextField5.getText()));
         
    pay.setInt(7,Integer.valueOf(cx));
    int rsdets= pay.executeUpdate();
}

CodePudding user response:

As Jens mentioned. You're attempting to cast a double/float value to int. So depending on what you're trying to do.

  1. If you're accepting decimal points, then it's better to change your DB schema to accept decimal and use Double.valueOf(cx).

  2. If you're accepting Integer only, then you have to parse the input and either truncate or round off the decimal points. (int) Math.round(Double.valueOf(cx))

    • Some people multiply the amount by 100 to include cents as a way to bypass dealing with doubles

Edit: Can you post the stacktrace? Looking more closely at the code, cx is already an integer and you're doing Integer.valueOf(cx) which does nothing. Also isn't cx always 0 since you're doing k-k? Are you sure the IDs are string values? That part looks weird to me.

CodePudding user response:

396.00 is a Double not an int value. So you have to parse it as a double:

Double.valueOf(cx).intValue() 

So your code looks like:

if(jCheckBox1.isSelected())
      {
          String bx="Insert into supplierpaymenttable(Supplier_ID,SupplierInvoice_ID,User_ID,InvoiceNo,TotalAmount,PaymentAmount,RemainingBalance) VALUES (?,?,?,?,?,?,?)";
          
        
  
           PreparedStatement pay=conn.prepareStatement(bx);
             int k=Double.valueOf(jTextField5.getText()).intValue();
               int cx=k-k;
        

       pay.setString(1,String.valueOf(supplier));
       pay.setString(2,String.valueOf(det));
       pay.setString(3,"1");
       pay.setString(4, String.valueOf(invoie));
       pay.setInt(5, Integer.valueOf(jTextField5.getText()));
       pay.setInt(6, Integer.valueOf(jTextField5.getText()));
     
       pay.setInt(7,Double.valueOf(cx).intValue());
         int rsdets= pay.executeUpdate();
      }
  • Related