This week's giveaway is in the Android forum.
We're giving away four copies of Android Security Essentials Live Lessons and have Godfrey Nolan on-line!
See this thread for details.
The moose likes Beginning Java and the fly likes validate number Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Android Security Essentials Live Lessons this week in the Android forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "validate number" Watch "validate number" New topic

validate number

Raj Ohadi
Ranch Hand

Joined: Jun 30, 2006
Posts: 316
If I want to make sure the input string is a valid number. It can be integer or double, with or without decimal. it can allow a "+" sign in front of it. But it can not be zero or negative. Of course it has to be a number (can't be string or char or things like that). what's the best way to validate this ?
M K Rayapudi
Ranch Hand

Joined: Feb 19, 2007
Posts: 157
There may be several possibilities,
In my opinion
1. Accept the input as string and then perform all the validations in pure java.
2. Make use of regex (regular expressions).
3. Java 6 supports Javascript, so that, you can make use of javascript, for reference hava a look here

my suggestion is, better to use regex.
Campbell Ritchie

Joined: Oct 13, 2005
Posts: 38087
Agree about using a regex. The grammar for number literals in Java can be found in the Java™ Language Specification and you can probably find example regexes on the Net. Here, for example.

I found 0|[1-9][0-9]* as a regular expression for integers on the website for JFlex. Note the + or - sign is not part of the number in Java.
Rahul P Kumar
Ranch Hand

Joined: Sep 26, 2009
Posts: 188
a regex like "\\+?[0-9]+\\.?[0-9]*" will solve the problem.
Consider Paul's rocket mass heater.
subject: validate number
Similar Threads
Related to drop down selecting multiple values
How to find if there is a number in a string using regular expressions.
how to Validate a String for decimal number in java script ?
validation- is it a number
how to validate a string like "20060503" is DATE