I have a String
that represents an integer value and would like to convert it to an int
. Is there a groovy equivalent of Java's Integer.parseInt(String)
?
13 Answers
Use the toInteger()
method to convert a String
to an Integer
, e.g.
int value = "99".toInteger()
An alternative, which avoids using a deprecated method (see below) is
int value = "66" as Integer
If you need to check whether the String
can be converted before performing the conversion, use
String number = "66"
if (number.isInteger()) {
int value = number as Integer
}
Deprecation Update
In recent versions of Groovy one of the toInteger()
methods has been deprecated. The following is taken from org.codehaus.groovy.runtime.StringGroovyMethods
in Groovy 2.4.4
/**
* Parse a CharSequence into an Integer
*
* @param self a CharSequence
* @return an Integer
* @since 1.8.2
*/
public static Integer toInteger(CharSequence self) {
return Integer.valueOf(self.toString().trim());
}
/**
* @deprecated Use the CharSequence version
* @see #toInteger(CharSequence)
*/
@Deprecated
public static Integer toInteger(String self) {
return toInteger((CharSequence) self);
}
You can force the non-deprecated version of the method to be called using something awful like:
int num = ((CharSequence) "66").toInteger()
Personally, I much prefer:
int num = 66 as Integer
As an addendum to Don's answer, not only does groovy add a .toInteger()
method to String
s, it also adds toBigDecimal()
, toBigInteger()
, toBoolean()
, toCharacter()
, toDouble()
, toFloat()
, toList()
, and toLong()
.
In the same vein, groovy also adds is*
eqivalents to all of those that return true
if the String
in question can be parsed into the format in question.
The relevant GDK page is here.
I'm not sure if it was introduced in recent versions of groovy (initial answer is fairly old), but now you can use:
def num = mystring?.isInteger() ? mystring.toInteger() : null
or
def num = mystring?.isFloat() ? mystring.toFloat() : null
I recommend using floats or even doubles instead of integers in the case if the provided string is unreliable.
The way to use should still be the toInteger()
, because it is not really deprecated.
int value = '99'.toInteger()
The String version is deprecated, but the CharSequence
is an Interface that a String implements. So, using a String is ok, because your code will still works even when the method will only work with CharSequence
. Same goes for isInteger()
See this question for reference : How to convert a String to CharSequence?
I commented, because the notion of deprecated on this method got me confuse and I want to avoid that for other people.