File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

isNumeric()

 
V Bose
Ranch Hand
Posts: 113
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Can someone suggest a neat trick to check whether an Object is one of the numeric primitive types int,float,short or double.
 
Ernest Friedman-Hill
author and iconoclast
Marshal
Pie
Posts: 24204
34
Chrome Eclipse IDE Mac OS X
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
An Object is never a primitive, by definition. Do you mean is it one of the primitive wrapper types, like Integer, Float, Long, etc? You could use "instanceof Numeric" (java.lang.Numeric is the superclass of all the numeric wrappers.) If you mean something else -- well, you'll have to clarify.
 
V Bose
Ranch Hand
Posts: 113
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I guess I'll change my question. Let's say I have a String. Is there a function to determine if it represents a numeric value ?
 
Wayne L Johnson
Ranch Hand
Posts: 399
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Try something like this:

In other words, attempt to convert it to a Double (or a Float or Integer, whatever is appropriate) and let the system determine if it's valid or not. If it throws an exception, it's not valid.
I suppose an alternative would be to test the String against a regular expression, but that could get ugly with the different formats that you'd have to support (integer, real, scientific notation, etc.)
[ October 29, 2003: Message edited by: Wayne L Johnson ]
 
Rafael Lee
Greenhorn
Posts: 23
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello V Bose,
Try to look at the Apache Jakarta Commons Lang package. It has a NumberUtils class that has a isNumber method which might satisfy what you want.

-------------------------------------------
Havin' dreams is what makes life tolerable! (can't recall who said this)
 
Stan James
(instanceof Sidekick)
Ranch Hand
Posts: 8791
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You could probably get real close to the right answer with regular expression matching, too. See Pattern in the API. I say real close, because it wouldn't check ranges.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic