Frage

I have this problem where I am trying to retrieve and pass calculated values to JformattedTextfield, I know 1,500.00 can not be accepted by Float due to the jformattedTextfield (,). Is there a way to bypass this issue ?

 private void SellButtonActionPerformed(java.awt.event.ActionEvent evt) {                                           
      float foreign , sellingRate, localAmount;
            try{
            DefaultTableModel dtm=(DefaultTableModel)p1.getModel();
            int i = p1.getSelectedRow();
            String s1=dtm.getValueAt(i,2).toString();
            txt_rate.setText(s1);
      }catch(Exception e){
          JOptionPane.showMessageDialog(null, "Select Currency First");
      }
            foreign =  Float.parseFloat(txt_select.getText());
            sellingRate =  Float.parseFloat(txt_rate.getText());
            localAmount = foreign / sellingRate;
            txt_amount.setValue(localAmount);
        }  

Error Message

Exception in thread "AWT-EventQueue-0" java.lang.NumberFormatException: For input string: "1,500.00"
        at sun.misc.FloatingDecimal.readJavaFormatString(FloatingDecimal.java:1241)
        at java.lang.Float.parseFloat(Float.java:452)

under thousand unite

I can calulate numbers under {1,000}

Expected result Expected result

War es hilfreich?

Lösung

Do you really want to let the user input the currency with a thousands separator? At least to all applications I have seen and developed so far, this is very uncommon.

Usually you only use it for display purposes, not for input. So the user would enter 1000 and you'll display it as 1,000.00 by formatting the value by NumberFormat.format().

If you really want the input like that, it should be treated as a String and then be parsed by NumberFormat.parse() as shown here.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top