Ravi Longia
Ravi Longia

Reputation: 15

Couldn't Convert jTextfield string into float value..... Giving number format exception

Im experiencing a problem in parsing jTextfield into float value so i can perform operation but its giving number format exception

Here is the Error

Exception in thread "AWT-EventQueue-0" java.lang.NumberFormatException: empty String
    at sun.misc.FloatingDecimal.readJavaFormatString(FloatingDecimal.java:1011)
    at java.lang.Float.parseFloat(Float.java:452) 

and this is what im doing

float T1 = Float.parseFloat(txt_T1_f.getText());

Upvotes: 0

Views: 5587

Answers (3)

Mohsen Kamrani
Mohsen Kamrani

Reputation: 7457

First you should check your string to find out is it a float at all? try this:

    String regex="^([+-]?\\d*\\.?\\d*)$";
    String input = txt_T1_f.getText();
    float T1 ;
    if(Pattern.matches(regex, input)){
        T1 = Float.valueOf(input);
    }

Upvotes: 0

Boris
Boris

Reputation: 24443

You can add a check on the text value like this:

String text = txt_T1_f.getText();
if (text != null && !text.isEmpty()) {
    float T1 = Float.parseFloat(text);
}

Upvotes: 1

Rahul
Rahul

Reputation: 3509

Before converting to float, check your string is not empty and not null. You are getting excepting since your string is empty.

use

  if(txt_T1_f.getText()!=null && !txt_T1_f.getText().isEmpty())
  float T1 = Float.parseFloat(txt_T1_f.getText());

Upvotes: 0

Related Questions