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)
?
views:
1303answers:
4Well, 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
Several ways to do it, this one's my favorite:
def number = '123' as int
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
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.