File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Java in General and the fly likes isNumeric() Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "isNumeric()" Watch "isNumeric()" New topic
Author

isNumeric()

V Bose
Ranch Hand

Joined: Jul 10, 2003
Posts: 113
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

Joined: Jul 08, 2003
Posts: 24183
    
  34

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.


[Jess in Action][AskingGoodQuestions]
V Bose
Ranch Hand

Joined: Jul 10, 2003
Posts: 113
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

Joined: Sep 03, 2003
Posts: 399
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

Joined: Sep 06, 2003
Posts: 23
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

Joined: Jan 29, 2003
Posts: 8791
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.


A good question is never answered. It is not a bolt to be tightened into place but a seed to be planted and to bear more seed toward the hope of greening the landscape of the idea. John Ciardi
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: isNumeric()