Granny's Programming Pearls
"inside of every large program is a small program struggling to get out"
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
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: 160
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: 46337
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.
I agree. Here's the link:
subject: validate number
It's not a secret anymore!