• Post Reply Bookmark Topic Watch Topic
  • New Topic

Converting String to Number  RSS feed

 
Kumar Abhinav
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
I have a String....Now how do i check whether its a Number(int, Long, Double) or not ??
 
dhwani mathur
Ranch Hand
Posts: 621
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Can you please ellaborate and explain what is your doubt,once understood than it
will be easier to explain...
 
Kumar Abhinav
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have a String str. Now i need to check whether the contents of this String represent a valid Number or not. This number can be an int or a long. One of the methods that i know is to make a function like this :

public boolean checkNumber(String str)
{
boolean result = true;
for(int i=0;i<str.length();i++)
{
if(!((str.charAt(i)>=0) && (str.charAt(i)<=9)))
{
result = false;
break;
}
}
return result;
}

I just want to know if there exist anyother way out wherein i use only library functions to solve this problem.
 
Prafulla N. Patil
Ranch Hand
Posts: 106
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
use regular expressions in java

Click here for regular expressions
 
Stan James
(instanceof Sidekick)
Ranch Hand
Posts: 8791
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The lowest effort way might be to try to use parse methods on the wrapper classes. Look at the JavaDoc for Integer and see if you find a method that fits the bill.

This is low effort, but has some cons for heavy use in production systems. Would that be a concern to you?
 
dhwani mathur
Ranch Hand
Posts: 621
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
well!!the hint given by Stane is too gud......

i can add it to somthing in this as below.......just take the input from user as String
BufferedReader buff=new BufferedReader(new InputStreamReader(System.in));

Now use the method of wrapper class Integer
int i;
i=Integer.parseInt(buff.readLine());//Integer.pareseInt method returns the integer value...
System.out.println(i);


The method buff.readLine() will read value as string but using later method we can convert it to integer and save it in integer i......than you can compare i with a list of value between 0 to 10........

i hope it helps..............
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!