String myString = "1234";
int foo = Integer.parseInt(myString);
If you look at the Java Documentation you'll notice the "catch" is that this function can throw a NumberFormatException, which of course you have to handle:
int foo;
try {
foo = Integer.parseInt(myString);
}
catch (NumberFormatException e)
{
foo = 0;
}
(This treatment defaults a malformed number to 0, but you can do something else if you like.)
Alternatively, you can use an Ints method from the Guava library, which in combination with Java 8's Optional, makes for a powerful and concise way to convert a string into an int:
import com.google.common.primitives.Ints;
int foo = Optional.ofNullable(myString)
.map(Ints::tryParse)
.orElse(0)
String mystr = mystr.replaceAll("[^\\d]", ""); int number = Integer.parseInt( ...
We can convert String to an int in java using Integer.parseInt() method. To convert String into Integer, we can use Integer.valueOf() method which returns ...
String str="-1122"; int inum = Integer.valueOf(str);. Value of inum would be -1122. Similar to the parseInt(String) ...
Common ways to convert an integer · 1. The toString() method. This method is present in many Java classes. It returns a string. · 2. String.valueOf() · 3.
Constructs a newly allocated Integer object that represents the int value indicated by the String parameter. Method Summary. Methods. Modifier and Type, Method ...
2、 int i = Integer.valueOf(my_str).intValue();. 注: 字串转成Double, Float, Long 的方法大同小异. 2 如何将整数int 转换成字串String ?