| Author |
String to number
|
Sarone Thach
Ranch Hand
Joined: Jun 25, 2003
Posts: 89
|
|
hi there, I would like to check if the string i got is a valid number. for example a "abc" will false. "123" will return true. I have tried new Integer("abc"); but I get a NumberFormatException. Is there another way to check that the string is a valid number without getting exceptions? thanks heaps, sarone
|
 |
Ernest Friedman-Hill
author and iconoclast
Marshal
Joined: Jul 08, 2003
Posts: 24081
|
|
|
Write a short function which calls Integer.parseInt() inside a try block. If it succeeds, the routine should return "true"; from the catch block, it should return "false". That's the best you're going to do short of writing your own little number-parsing routine.
|
[Jess in Action][AskingGoodQuestions]
|
 |
Mani Ram
Ranch Hand
Joined: Mar 11, 2002
Posts: 1140
|
|
|
Or use Double.parseDouble() method to handle floating numbers and large numbers.
|
Mani
Quaerendo Invenietis
|
 |
Naren Chivukula
Ranch Hand
Joined: Feb 03, 2004
Posts: 542
|
|
Ernest and Mani gave nice solutions and I hereby give u one more solution which comes from basic understanding. If the string does contain all digits then it will return true. Use ASCII code to write a If block to perform this.
|
Cheers,
Naren (SCJP, SCDJWS and SCWCD)
|
 |
Mani Ram
Ranch Hand
Joined: Mar 11, 2002
Posts: 1140
|
|
Originally posted by Naren Chivukula: If the string does contain all digits then it will return true. Use ASCII code to write a If block to perform this.
And write additional code to handle unary minus & decimal points (like there can be atmost one decimal point & one minus sign, and if the minus sign is present, it should be the first character of the string etc), if required.
|
 |
Naren Chivukula
Ranch Hand
Joined: Feb 03, 2004
Posts: 542
|
|
Mani has pointed out correctly. Check unary plus/unary minus/decimal point. If you are expecting binary/octal/hexal. check the string accordingly.
|
 |
Sadanand Murthy
Ranch Hand
Joined: Nov 26, 2003
Posts: 382
|
|
Originally posted by Naren Chivukula: Ernest and Mani gave nice solutions and I hereby give u one more solution which comes from basic understanding. If the string does contain all digits then it will return true. Use ASCII code to write a If block to perform this.
Why would you want to do this when you can convert the string into a char[] & Character has isDigit method?
|
Ever Existing, Ever Conscious, Ever-new Bliss
|
 |
Layne Lund
Ranch Hand
Joined: Dec 06, 2001
Posts: 3061
|
|
As you can see, there IS a way to avoid exceptions altogether. Personally, I like using the Integer.parseInt() method and dealing with the exception that is thrown. This usually takes fewer lines of code. Of course, doing it the "old fashioned way" is a good academic exercise, if nothing else. Layne [ February 20, 2004: Message edited by: Layne Lund ]
|
Java API Documentation
The Java Tutorial
|
 |
 |
|
|
subject: String to number
|
|
|