3

I am casting my String variables to integer and double. I want to check whether the String variable contains valid Integer or Double value at runtime.

I us following code but it not works for me.

String var1="5.5";
String var2="6";
Object o1=var1;
Object o2=var2;
if (o1 instanceof Integer)
{
    qt += Integer.parseInt( var1);// Qty
}
if (o2 instanceof Double)
{
    wt += Double.parseDouble(var2);// Wt
}
Rohit Jain
  • 209,639
  • 45
  • 409
  • 525

5 Answers5

5

Try to parse the int and catch the exception if it fails:

String var1="5.5";

try {
 qt += Integer.parseInt( var1);
}    
catch (NumberFormatException nfe) {
// wasn't an int
}
blank
  • 17,852
  • 20
  • 105
  • 159
  • I know this technique but i want to avoid excpetion to occur – Syed Muhammad Mubashir Nov 27 '12 at 08:18
  • 1
    @SyedMuhammadMubashir.. This is what we call avoiding Exception to occur. We should handle them. And whether exception is raised or not, completely depends upon what string you are trying to convert. Of course you cannot convert `""`. – Rohit Jain Nov 27 '12 at 08:19
  • You might want to look at http://stackoverflow.com/questions/9619603/no-tryparsedouble-in-java, or the question that one is a duplicate of. – TheBlastOne Nov 27 '12 at 08:53
3

First of all, your if condition will certainly fail, because the object reference actually points to a String object. So, they are not instances of any integer or double.

To check whether a string can be converted to integer or double, you can either follow the approach in @Bedwyr's answer, or if you don't want to use try-catch, as I assume from your comments there (Actually, I don't understand why you don't want to use them), you can use a little bit of pattern matching: -

String str = "6.6";
String str2 = "6";

// If only digits are there, then it is integer
if (str2.matches("[+-]?\\d+")) {  
    int val = Integer.parseInt(str2);
    qt += val;
}

// digits followed by a `.` followed by digits
if (str.matches("[+-]?\\d+\\.\\d+")) {  
    double val = Double.parseDouble(str);
    wt += val;
}

But, understand that, Integer.parseInt and Double.parseDouble is the right way to do this. This is just an alternate approach.

Rohit Jain
  • 209,639
  • 45
  • 409
  • 525
3

You can use patterns to detect if a string is an integer or not :

  Pattern pattern = Pattern.compile("^[-+]?\\d+(\\.\\d+)?$");
  Matcher matcher = pattern.matcher(var1);
  if (matcher.find()){
      // Your string is a number  
  } else {
      // Your string is not a number
  }

You will have to find the correct pattern (I haven't used them for awhile) or someone could edit my answer with the correct pattern.

*EDIT** : Found a pattern for you. edited the code. I did not test it but it is taken from java2s site which also offer an even more elgant approach (copied from the site) :

 public static boolean isNumeric(String string) {
      return string.matches("^[-+]?\\d+(\\.\\d+)?$");
  }
giorashc
  • 13,691
  • 3
  • 35
  • 71
3

Maybe regexps could suit your needs:

public static boolean isInteger(String s) {
    return s.matches("[-+]?[0-9]+");
}

public static boolean isDouble(String s) {
    return s.matches("[-+]?([0-9]+\\.([0-9]+)?|\\.[0-9]+)");
}

public static void main(String[] args) throws Exception {
    String s1 = "5.5";
    String s2 = "6";
    System.out.println(isInteger(s1));
    System.out.println(isDouble(s1));
    System.out.println(isInteger(s2));
    System.out.println(isDouble(s2));
}

Prints:

false
true
true
false
sp00m
  • 47,968
  • 31
  • 142
  • 252
  • @SyedMuhammadMubashir Are you dealing reputation?! I won't upvote your question, but you're free not to upvote mine ;) – sp00m Nov 27 '12 at 10:11
  • @SyedMuhammadMubashir.. I assume that you are asking questions on SO, to learn something, and not to buy Reputation. If you are doing so for the later, then rather answer the questions here. And give very good answers, if you know them. Don't urge people here to upvote your posts. – Rohit Jain Nov 27 '12 at 10:20
1

Integer.parseInt and Double.parseDouble return the integer/double value of the String. If the String is not a valid number, the method will thrown a NumberFormatException.

String var1 = "5.5";

try {
    int number = Integer.parseInt(var1); // Will fail, var1 has wrong format
    qt += number;
} catch (NumberFormatException e) {
    // Do your thing if the check fails
}

try {
    double number = Double.parseDouble(var1); // Will succeed
    wt += number;
} catch (NumberFormatException e) {
    // Do your thing if the check fails
}
Thorkil Holm-Jacobsen
  • 7,287
  • 5
  • 30
  • 43