Grails Cookbook - A collection of tutorials and examples

Groovy String To Integer

Here are different examples of how to convert a Groovy String To Integer.

Using toInteger()

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() : null

The variable intValue will have the value null if strnumber is not a valid integer.

Using as int

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

Using Integer.parseInt()

We can also use Integer.parseInt() as Groovy is a superset of Java

def strnumber = "100"
def intValue = Integer.parseInt(strnumber)

Using Integer.valueOf()

Similar to parseInt, we can also use Integer.valueOf()

def strnumber = "100"
def intValue = Integer.valueOf(strnumber)

Using new Integer(String).intValue()

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)

Using DecimalFormat

Here is another approach using Java's DecimalFormat.

def strnumber = "100"
DecimalFormat decimalFormat = new DecimalFormat("#");
def intValue = decimalFormat.parse(strnumber).intValue();

Other Groovy Tutorials