Solved

Function for finding out if a varible holds a number i.e., IsNumber()?

Posted on 2004-08-25
20
841 Views
Last Modified: 2007-12-19
I need to know if a variable contains a number or not.
I have some conditional formatiing that is taking place, and the variable could either be set to nothing, null, or a number.  Is there a JSP function like this?

String myvar = null
myvar = request.getParameter("myvar");
if(myvar.IsNumber()){
     //Do Something
}else{
     //Do Something else...
}

Thanks in advance,
-MD
0
Comment
Question by:mderbin
  • 6
  • 5
  • 4
  • +1
20 Comments
 
LVL 27

Expert Comment

by:rrz
ID: 11898940
Did you try that code ? won't it throw a null pointer ?  

String myvar = null
myvar = request.getParameter("myvar");
if(myvar != null && myvar.IsNumber()){
     //Do Something
}else{
     //Do Something else...
}  

Maybe  you  should look at JSTL if you are looking for functions.   rrz
0
 
LVL 27

Expert Comment

by:rrz
ID: 11898966
Here is old article ( we are using JSTL 1.0 ).
http://java.sun.com/developer/technicalArticles/javaserverpages/faster/
0
 
LVL 27

Expert Comment

by:rrz
ID: 11898970
>we are using JSTL 1.0 ).
No, we are using  1.1  now  !
0
 
LVL 27

Accepted Solution

by:
rrz earned 32 total points
ID: 11899226
You could use something like the following.  
<%
      try{ Integer.parseInt(myvar);
                                 out.print("myvar is a number");
      }
         catch(NumberFormatException nfe){
                                out.print("myvar is not a number");
         }
%>

But hopefully someone  else has something prettier.                 rrz
0
 
LVL 27

Expert Comment

by:rrz
ID: 11899265
Or we could use
Float.parseFloat(myvar);
in same way as the above code.
0
 
LVL 35

Assisted Solution

by:TimYates
TimYates earned 31 total points
ID: 11900266
I think rrz's way of catching the parse exception is the only way...
0
 
LVL 14

Expert Comment

by:boonleng
ID: 11900782
You can use regex to check whther the value is a number:
JDK 1.3 needs to use org.apache.regexp.RE, JDK 1.4 can do regex in String object.

RE re = new RE("^[0-9\\.]+$");
if (re.match(value)) {
}
0
 
LVL 35

Expert Comment

by:TimYates
ID: 11900824
That doesn't work, as

     System.out.println( java.util.regex.Pattern.matches( "^[0-9\\.]+$", "0.3.2") ) ;

prints "true"
0
 
LVL 14

Assisted Solution

by:boonleng
boonleng earned 31 total points
ID: 11900947
opps...
modify a bit, try to use pattern {n} but cant seem to get it work, so check base on index.
any better suggestion?

      RE re = new RE("^[0-9\\.]+$");
      if (re.match(value)) {
            int idx = value.indexOf(".");
            if (idx > -1) {
                  return !(value.indexOf(".", idx + 1) > -1);
            }
            return true;
      }
0
Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

 
LVL 35

Expert Comment

by:TimYates
ID: 11900956
> any better suggestion?

yes, the way rrz@871311 does it ;-)
0
 
LVL 14

Expert Comment

by:boonleng
ID: 11900990
hmm... true also :)
0
 
LVL 3

Expert Comment

by:pat5star
ID: 11904934
How about this?

    public static boolean isNumber(String in) {
        if (null == in || in.trim().length() == 0) return false;
        return in.matches("\\d+");
    }

0
 
LVL 35

Expert Comment

by:TimYates
ID: 11905096
>  How about this?

Will that work for 5.3?
0
 
LVL 3

Expert Comment

by:pat5star
ID: 11905220
No, but this will:

    public static boolean isNumber(String in) {
        if (null == in || in.trim().length() == 0) return false;
        return in.matches("\\d*(?:\\.?\\d+)?");
    }

This allows any number. If the variable contains a decimal it must have at least 1 number following it. Here are some example results:

.321 = true
2.45 = true
23.1 = true
23.   = false
230  = true
0
 
LVL 35

Expert Comment

by:TimYates
ID: 11906811
what about

9.0E-3

?

;-)

My point here, is that the best way of doing it is rrz's way that he posted first ;-)
0
 
LVL 3

Assisted Solution

by:pat5star
pat5star earned 31 total points
ID: 11907292
If the OP specifies his exact requirements (like whether he has to handle cases like your last example) then the proper regex can be built to handle that. I disagree that rrz's method is the best way to do it. Checking whether something is true or not by determining whether an exception is thrown is a bad design pattern. I was also going to back this argument up by mentioning that it would be more expensive to test this way but I was suprised by the results.

Running this code:

import java.util.regex.Pattern;
import java.util.regex.Matcher;

public class FindNumber {
   
    private static final Pattern p = Pattern.compile("\\d*(?:\\.?\\d+)?");
   
    public static void main(String[] args) {
        double start, end;
       
        // Use regex, isNumber1()
        start = System.currentTimeMillis();
        for (int i=0; i<1000000; i++) {
            isNumber1("55.55");
        }
        end = System.currentTimeMillis();
        System.out.println("Method using regex completed in " + (end - start)/1000 + " seconds.");
       
        // Use exception check, isNumber2()
        start = System.currentTimeMillis();
        for (int i=0; i<1000000; i++) {
            isNumber2("55.55");
        }
        end = System.currentTimeMillis();
        System.out.println("Method using exception check completed in " + (end - start)/1000 + " seconds.");
       
        // Use regex, with regex pattern precompiled, isNumber3()
        start = System.currentTimeMillis();
        for (int i=0; i<1000000; i++) {
            isNumber3("55.55");
        }
        end = System.currentTimeMillis();
        System.out.println("Method using regex with regex pattern precompiled completed in " + (end - start)/1000 + " seconds.");
    }
   
    public static boolean isNumber1(String in) {
        if (null == in || in.trim().length() == 0) return false;
        return in.matches("\\d*(?:\\.?\\d+)?");
    }
   
    public static boolean isNumber2(String in) {
        try {
            float value = Float.parseFloat(in);
            return true;
        } catch (NumberFormatException ignored) {
            return false;
        }
    }
   
    public static boolean isNumber3(String in) {
        if (null == in || in.trim().length() == 0) return false;
        Matcher m = p.matcher(in);
        return m.matches();
    }
}

Resulted in these benchmarks:

Method using regex completed in 5.579 seconds.
Method using exception check completed in 0.593 seconds.
Method using regex with regex pattern precompiled completed in 1.641 seconds.

So my last argument is out the window :P

Whatever the OP chooses to use is up to him. It seems wrong to me to use isNumber2() but the benchmarks don't lie! I really expected the regex method to be much faster. Either way, I found this topic interesting and learned something new today :)

-Pat
0
 
LVL 3

Expert Comment

by:pat5star
ID: 11908794
Those results were bugging me today so I thought about it more and realized what made the exception check method so much faster. The test was with a valid float so the isNumber2() method never once threw an exception. If you use a value for the test that isn't a valid float, the benchmarks show a whole different picture:

Method using regex completed in 5.796 seconds.
Method using exception check completed in 9.125 seconds.
Method using regex with regex pattern precompiled completed in 1.891 seconds.

That makes isNumber3() look a whole lot better :)

-Pat

0
 
LVL 27

Expert Comment

by:rrz
ID: 11909478
>Is there a JSP function like this?
There probably should be one.  
Javascript has isNaN() .
Why not validate before  submission ?
Here is another way.

    public static boolean isNumber(String var){
                          int pointCount = 0;
                          for(int i=0;i<var.length();i++){
                                   char c = var.charAt(i);
                                   if(var.charAt(i) == '.')pointCount++;
                                   if(!Character.isDigit(c)|| pointCount > 1) return false;
                          }
                          return true;
    }
0

Featured Post

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
jersey maven project error 7 137
dynamic reloading of jsp in jetty 2 118
Java Exception example issues 11 84
How to find missing packages when using Netbeans IDE 8.1 ? 19 46
We need a new way to communicate time sensitive or critical info.   The best part of my role at xMatters is visiting our clients all over the world to learn about how they operate their businesses, share insights that xMatters has gleaned across…
Some code to ensure data integrity when using macros within Excel. Also included code that helps secure your data within an Excel workbook.
Migrating to Microsoft Office 365 is becoming increasingly popular for organizations both large and small. If you have made the leap to Microsoft’s cloud platform, you know that you will need to create a corporate email signature for your Office 365…
Internet Business Fax to Email Made Easy - With  eFax Corporate (http://www.enterprise.efax.com), you'll receive a dedicated online fax number, which is used the same way as a typical analog fax number. You'll receive secure faxes in your email, f…

910 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

21 Experts available now in Live!

Get 1:1 Help Now