I'm new here... but I'm a computer freak (more than literally ). I am great at VB.NET... but I have a function which does not have a corresponding one in java: IsNumeric(String input). Does anyone know how to find out whether a String is a number (int or floating-point)? Thanks. P.S.: Please do not tell me about Character.IsDigit - I don't want loops!
P.S.: Please do not tell me about Character.IsDigit - I don't want loops!
Whats the matter with loops. Any solution given will probably (whether expilcitly or internally) have to loop through each character in the string and see if its a digit or a '.' (although not more than one). What kind of solution were you interested in?
Some problems are so complex that you have to be highly intelligent and well informed just to be undecided about them. - Laurence J. Peter
Note that the original question allowed for floating-point as well. Ignoring the possibility of exponential notation, this suggests a more elaborate regex like:
Unfortunately that's a bit involved for the beginner forum. So, Lambert: if you are familiar with regular expressions, or are sufficiently motiviated to learn more about them, I recommend something like the above. (Note that I haven't tested it, so don't be too trusting that everything there is correct.) If not, well, the try/catch with Double.parseDouble() that Garrett suggested is the simplest thing to code.
Here is a more optimized regex for detecting floating point numbers -- no need for grouping or the OR operator.
Henry [ October 31, 2006: Message edited by: Henry Wong ]
Joined: Jan 30, 2000
Yeah - though that will reject something like "42.", which may or may not be something the user might expect to be able to enter. Such a format is legal for a floating-point literal in Java, after all. Though most people would use "42" or "42.0" instead.
I know that I am late to party here, but here is some more info on this topic, solving the numeric check by using Apache Commons, more info here: Stack Overflow (http://stackoverflow.com/a/3507236/549510).