Search code examples
javatype-conversionparseintnumberformatexception

Converting string into a readable int from a JLabel


I need to apply an interest method to a number in a JLabel. I can manage to do it from a Jtextfield, but for some reason I cannot get it to work on the JLabel.

Here is the code that is initiated when the Jbutton is pressed:

private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {                                         
    interest(Integer.parseInt(balanceLabel.getText()));

balanceLabel is the name of the label I am trying to work with.

Here is the error that is returned when I press the button:

Exception in thread "AWT-EventQueue-0" java.lang.NumberFormatException: For input string: "£1000.0"
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)

I have researched the problem and it seems it is extremely common but for some reason I cannot apply other answers to my situation as I lack the knowledge to do so.


Solution

  • The problem is the £ AND the . since you are trying an int conversion.

    Use a float instead:

    Float.parseFloat(balanceLabel.getText().substring(1));
    

    This way you can have decimal values, which makes sense for currency.