Question: How do I convert a String to an int or a float?
Here's a sample Java program that shows how to convert a String to either an int or a float:
package com.devdaily.javasamples;
public class ConvertStringToNumber
{
public static void main(String[] args)
{
try
{
String s = "5";
int i = Integer.parseInt(s);
System.out.println("int value = " + i);
float f = Float.parseFloat(s);
System.out.println("float value = " + f);
}
catch (NumberFormatException nfe)
{
System.err.println(nfe.getMessage());
}
}
}
As you can see from the sample code, the trick is to use either the parseInt method of the Integer class, or the parseFloat method of the Float class to perform the conversion. As either of these methods can throw a NumberFormatException you should either handle that exception, or let it be thrown by your method.
Post new comment