• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

validate number

 
Raj Ohadi
Ranch Hand
Posts: 316
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 160
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Sheriff
Pie
Posts: 50175
79
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 188
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
a regex like "\\+?[0-9]+\\.?[0-9]*" will solve the problem.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic