Login | Register   
LinkedIn
Google+
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


Tip of the Day
Language: Java Language
Expertise: Beginner
Mar 21, 1997

Converting from String to Integer or Float

Question:
How can I convert a String type value to an integer or float? For example,
String str="155.230";
float  real;
real = str.HowCanIConvert???????;
 
I've tried it like this:
Integer aValue = new Integer(String.valueOf("1")); 
But this method doesn't always work. What's the problem?

Answer:
You're lucky your solution worked at all! Probably, the method:

  public static String valueOf(Object obj)  
was being called, as I see no variant of String.valueOf() that expects a String parameter.

Perhaps you intended

Integer.valueOf("1"); 
Of course this only returns an Integer. To get an int, you'll need to compose it with another conversion:
int i = intValue(Integer.valueOf("1")); 
For floats, you need to first convert to a Float, then convert to a float:
float f = floatValue(Float.valueOf("155.230"));
 
Java also provide a parseInt method. Try this:
   int i = Integer.parseInt("1"); 
DevX Pro
 
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap
Thanks for your registration, follow us on our social networks to keep up-to-date