Converting a string to int in Groovy

Viewed 377506

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
def str = "32"

int num = str as Integer

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.

The Simpler Way Of Converting A String To Integer In Groovy Is As Follows...

String aa="25"
int i= aa.toInteger()

Now "i" Holds The Integer Value.

Related