Hi every one,
Can anyone give me some idea about this!
I need to check a string is numeric or not.

Example:

if string is 1111111111 returns true
if string is 11111111aa returns false
if string is 11 1111111 returns false
if string is 111~`11111 returns false

Any idea will be nice.. thanks a lot...

Currently i was doing something like this..

for (int i = 0; i < chrArray.length; i++) {
                    if ((chrArray[i] >= 'A' && chrArray[i] <= 'Z') || (chrArray[i] >= 'a' && chrArray[i] <= 'z')) {
                        hasAlphaAgain = true;
                        break;
                    }
                }

but i also need to have a check for special characters

Thanks in advance!

Recommended Answers

All 12 Replies

I have more than onw suggestions for you.

1) instead of checking if it is a letter or a special character. you could check if it is a number between 0 to 9 so if all the characters are numbers you have number. it will be a lot easier for you.
2) even though you have a nice way to get the job done I suggest you use some of prewriten classes from. java api. for example. Character class has nice features that you can use. for example you can use isDigit() function to get if the character is a digit or not. anything you wanna do with a character you can do it with this class.

3) if you wont use very big values ,you can use Integer.parseInt method() if you try to give it anything other that digits you will get an exception that you have to catch. if you need bigger values use Long.parseLong()

those are the ones that I can remember. I hope that would help.

All of the above suggestions are valid and using a regex pattern is another option. Regex will allow a pretty complex input string to be validated rather simply.

i have done something like this before i used it for doubles. TYPE_WRAPPER.parseTYPE() will return a number of type TYPE. if you need a boolean value of whether it is or is not a number you can do this:

public boolean isIntNumber(String num){
    try{
        Integer.parseInt(num);
    } catch(NumberFormatException nfe) {
        return false;
    }
    return true;
}

this will work with all primitive number types. float, long, int, and double, all that needs to be changed is the name of the method the wrapper class and the type of the method.

I remember during my college days when I was a lazy programmer I used to use the BigDecimal and BigInteger classes for checking whether a particular string is numeric or float.

To check if a given number is an integer or not I used to just write the code

try{
  new java.math.BigInteger(<string to check>);
  System.out.println("String is numeric");
}catch(NumberFormatException ex) {
  System.out.println("String has invalid characters.");
}

same way to check for floating point numbers with the java.math.BigDecimal class.

But in recent times since I have learnt of regexes I no longer find the above approach attractive I prefer using the matches(String regex) function of the String class which is a much much better option.
Also if you are unaware of regexes in Java you can start here

Thanks for all the above replies.. My problem is solved and have used the regexes in Java .. here is one more methods i would like to share as this topic is becoming interesting..

for (int i = 0; i < str.length(); i++) {

            //If we find a non-digit character we return false.
            if (!Character.isDigit(str.charAt(i)))
                return false;
        }
       
        return true;
class IsitNumb
{
    public static void main(String[] args) 
    {
        System.out.println(isNumb("12345678"));
    }
public static boolean isNumb(String str)
{
    String s=str;
      for (int i = 0; i < s.length(); i++) {
      //If we find a non-digit character we return false.
      if (!Character.isDigit(s.charAt(i)))
          return false;
            }
          return true;
}
}

Thank you gays u have been very helpful!!!!!!!!

I just have to say Jun 26th, 2008 7:20 am thread started, solved: January 24th, 2012 8:56 pm. :) now thats legendary lol

Hi,

I have made few modification of code. Because having to return is not a good algorithmic issue.

I prefer using a flag when I want doing this example :

    boolean flag = true;

    for(int i=0; i<saisie.length(); i++) {
        if(!Character.isDigit(saisie.charAt(i))) {
            flag = false;
        }
    }

    return flag;

So, your modification continues to loop even after the result is known. Seems pointless, doesn't it?

There is no "algoritmic issue" with the returning once the condition is met. A flag may be your preference, but it's not more correct.

It's certainly not worth resurrecting this old thread to add.

As Ezzaral aluded to If you're going to flag, perhaps do something useful with it? Why check every digit if you don't need to.

 boolean flag = true;
 for(int i=0; i<saisie.length() && flag; i++) {
     flag=Character.isDigit(saisie.charAt(i));
 }
 return flag;

Here's an issue that fails on though: Isn't -123 a number? What about -3.141529?

Regex is ok except that '-' is an escapable char. As is '.' You can CERTAINLY write a regex match that will allow for that, but since you're going to have to check for the - in the first position only, your code may not be readable by people who aren't strong in regex.

stephen84s solution is the best imho

try{
   new java.math.BigInteger(<string to check>);
   return true;
}catch(Exception ex) {
}
return false;

Above solutions are horrible.

Glad to read the OP used regexp, but he didn't share the code for it. Here is how you do it with regexp:

return myString.matches("\\d*");

Get started with regexp with this tutorial Click Here

commented: I suggested regex in the third post - three years ago. Thanks for reading before adding your condescension. -3
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.