Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting a string to int in Groovy

Tags:

groovy

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

like image 792
Steve Kuo Avatar asked Nov 11 '09 06:11

Steve Kuo


People also ask

How do I convert a string to a float in Groovy?

Use Float. valueOf(String) to do the conversion.

How do I convert string to decimal in Groovy?

parseInt(String s) − This returns an integer (decimal only). parseInt(int i) − This returns an integer, given a string representation of decimal, binary, octal, or hexadecimal (radix equals 10, 2, 8, or 16 respectively) numbers as input.


2 Answers

Use the toInteger() method to convert a String to an Integer, e.g.

int value = "99".toInteger() 

An alternative, which avoids using a deprecated method (see below) is

int value = "66" as Integer 

If you need to check whether the String can be converted before performing the conversion, use

String number = "66"  if (number.isInteger()) {   int value = number as Integer } 

Deprecation Update

In recent versions of Groovy one of the toInteger() methods has been deprecated. The following is taken from org.codehaus.groovy.runtime.StringGroovyMethods in Groovy 2.4.4

/**  * Parse a CharSequence into an Integer  *  * @param self a CharSequence  * @return an Integer  * @since 1.8.2  */ public static Integer toInteger(CharSequence self) {     return Integer.valueOf(self.toString().trim()); }  /**  * @deprecated Use the CharSequence version  * @see #toInteger(CharSequence)  */ @Deprecated public static Integer toInteger(String self) {     return toInteger((CharSequence) self); } 

You can force the non-deprecated version of the method to be called using something awful like:

int num = ((CharSequence) "66").toInteger() 

Personally, I much prefer:

int num = 66 as Integer 
like image 54
Dónal Avatar answered Oct 20 '22 09:10

Dónal


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

def number = '123' as int 
like image 30
Esko Avatar answered Oct 20 '22 08:10

Esko