This is one of the simplest way of converting a String to integer in Groovy.
def strnumber = "100" def intValue = strnumber.toInteger()
If the number is not a valid int (e.g. "abc"), then toInteger() will throw an exception. We can use isInteger() method to check first.
def strnumber = "100" def intValue = strnumber.isInteger() ? strnumber.toInteger() : nullThe variable intValue will have the value null if strnumber is not a valid integer.
Here is another simple example using "as int".
def strnumber = "100" def intValue = strnumber as int
Here is the equivalent if you don't like exceptions.
def strnumber = "100" def intValue = strnumber.isInteger() ? (strnumber as int) : null
We can also use Integer.parseInt() as Groovy is a superset of Java
def strnumber = "100" def intValue = Integer.parseInt(strnumber)
Similar to parseInt, we can also use Integer.valueOf()
def strnumber = "100" def intValue = Integer.valueOf(strnumber)
We can also create an Integer object and invoke it's intValue() method
def strnumber = "100" def intValue = = new Integer(strnumber).intValue()
Or maybe not invoke the intValue() method at all
def strnumber = "100" def intValue = = new Integer(strnumber)
Here is another approach using Java's DecimalFormat.
def strnumber = "100" DecimalFormat decimalFormat = new DecimalFormat("#"); def intValue = decimalFormat.parse(strnumber).intValue();