tags:

views:

1303

answers:

4

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)?

+4  A: 

Well, Groovy accepts the Java form just fine. If you are asking if there is a Groovier way, there is a way to go to Integer.

Both are shown here:

String s = "99"
assert 99 == Integer.parseInt(s)
Integer i = s as Integer
assert 99 == i
Michael Easter
+2  A: 

Several ways to do it, this one's my favorite:

def number = '123' as int
Esko
+6  A: 

This is the one true path to Grooviness:

"99".toInteger()

Aside: there really is no such thing as an int in Groovy. All primitive type references are converted to their equivalent Object wrapper type. For example if you run the following:

int i = 6
i.class.name

It prints:

java.lang.Integer

Don
Seconded and thirded.
Electrons_Ahoy
+1  A: 

As an addendum to Don's answer from yesterday, not only does groovy add a ".toInteger()" method to strings, 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.

Electrons_Ahoy