329

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

alex
  • 6,818
  • 9
  • 52
  • 103
Steve Kuo
  • 61,876
  • 75
  • 195
  • 257

13 Answers13

564

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
Dónal
  • 185,044
  • 174
  • 569
  • 824
  • 21
    Caveat emptor: you need to check the value with `isInteger()` first, because `toInteger()` will throw an exception if the string is not numeric. Same applies to `toFloat()`/`isFloat()` – Andres Kievsky Nov 12 '11 at 07:40
  • 8
    In the [2.1.6 api documentation](http://groovy.codehaus.org/gapi/org/codehaus/groovy/runtime/DefaultGroovyMethods.html) isInteger/toInteger are deprecated. What is the current best way to do this then? – pakman Aug 29 '13 at 16:38
  • 1
    Using Integer paramValue = params.int('paramName') isn't null safe though. If there is no param with the name "paramName" in the param map you get an exception about can't cast null to int. – Michael Dec 05 '13 at 21:15
  • In Grails, I type my controller action parameters, e.g. `def displayInvoice(Integer accountNumber, String accountType)`. Any binding errors will show up in the errors object and the parameter will be assigned the default value. See the docs for data binding. I believe this comes directly from Spring MVC. – Philip Feb 08 '15 at 03:49
  • 2
    just wanted to add, that since Groovy 1.8 `int` is indeed `int`. Groovy will still display the Integer class, because of boxing, but you will for example not be able to assign `null` to an `int`, which was possible in 1.0. We considered the change being non-critical, since you already could not use null as argument for a method call parameter of type `int`. This is all still different from Java, as in Java you cannot convert Integer to Long by a simple assignment or call an int taking method with a Long. – blackdrag Feb 25 '15 at 12:02
  • I just keep getting `No such property: isInteger for class: java.lang.String. Stacktrace follows[...]` – WhyNotHugo Jul 14 '15 at 21:18
  • 1
    @pakman `StringGroovyMethods.isInteger(String)` and `DefaultGroovyMethods.isInteger(CharSequence)` are deprecated in favor of [`StringGroovyMethods.isInteger(CharSequence)`](http://docs.groovy-lang.org/latest/html/gapi/org/codehaus/groovy/runtime/StringGroovyMethods.html#isInteger(java.lang.CharSequence)). Same goes for `toInteger()`. – bmaupin Jul 15 '15 at 17:42
  • @Hugo sounds like you're leaving off the parentheses. `'99'.isInteger()`, not `'99'.isInteger`. – Charles Wood Nov 02 '16 at 15:27
74

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

def number = '123' as int
Esko
  • 29,022
  • 11
  • 55
  • 82
  • 11
    Same problem as above, this will throw an exception if the string is not a number. Check with `isInteger()` first. – Andres Kievsky Nov 12 '11 at 07:43
  • 14
    @ank the question asked for an equivalent of `Integer.parseInt(String)` which also throws an Exception if the string is not a number, so given the question, I don't consider this a "problem" – Dónal Nov 04 '16 at 10:25
  • I believe this is the way Groovy intends it to be done. You can generally use 'as' as a type conversion for anything (Sometimes you may have to attach a converter method, like if you really want to do JFrame as Boolean or something crazy like that. – Bill K Apr 26 '22 at 21:05
31

As an addendum to Don's answer, 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.

Community
  • 1
  • 1
Electrons_Ahoy
  • 36,743
  • 36
  • 104
  • 127
  • 8
    This is the correct answer - check first with `isInteger()`, then do `toInteger()`... that is, unless you'd rather add a `try`/`catch` block :) but using exceptions for this is a bad idea. – Andres Kievsky Nov 12 '11 at 07:45
  • 2
    @anktastic I'd argue that my answer is more correct because the question asked for "a groovy equivalent of Java's Integer.parseInt(String)", i.e. an unchecked conversion – Dónal Dec 06 '13 at 00:32
27

I'm not sure if it was introduced in recent versions of groovy (initial answer is fairly old), but now you can use:

def num = mystring?.isInteger() ? mystring.toInteger() : null

or

def num = mystring?.isFloat() ? mystring.toFloat() : null

I recommend using floats or even doubles instead of integers in the case if the provided string is unreliable.

zett42
  • 25,437
  • 3
  • 35
  • 72
Shmaperator
  • 271
  • 3
  • 2
  • 3
    +1 best solution IMO as it includes null check in addition to type check before conversion – kaskelotti Jun 06 '13 at 04:59
  • I recommend against using floats or doubles because they are inherently inaccurate. As Groovy makes using BigDecimals as easy as any other Number, if you need more accuracy than an Integer, use that. Secondly, this approach seems safe, but the result can be that num == null, so you need to be careful with that – Hans Bogaards Feb 25 '16 at 20:10
  • For the first sample code, I guess you wanted to write `mystring.toInteger()` instead of `mystring.toFloat()`. So `def num = mystring?.isInteger() ? mystring.toInteger() : null` would be correct. – Sk8erPeter Feb 24 '19 at 22:03
17

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
  • 23,733
  • 7
  • 76
  • 107
7

also you can make static import

import static java.lang.Integer.parseInt as asInteger

and after this use

String s = "99"
asInteger(s)
Daniel Serodio
  • 4,229
  • 5
  • 37
  • 33
Andrey
  • 121
  • 2
  • 5
3

toInteger() method is available in groovy, you could use that.

Jay Bhalani
  • 4,142
  • 8
  • 37
  • 50
Aakarsh Gupta
  • 195
  • 1
  • 6
2

Several ways to achieve this. Examples are as below

a. return "22".toInteger()
b. if("22".isInteger()) return "22".toInteger()
c. return "22" as Integer()
d. return Integer.parseInt("22")

Hope this helps

Darth Shekhar
  • 115
  • 3
  • 16
1

Groovy Style conversion:

Integer num = '589' as Integer

If you have request parameter:

Integer age = params.int('age')
Hendrikto
  • 513
  • 4
  • 14
1
def str = "32"

int num = str as Integer
ratzip
  • 1,571
  • 7
  • 28
  • 53
0

Here is the an other way. if you don't like exceptions.

def strnumber = "100"
def intValue = strnumber.isInteger() ?  (strnumber as int) : null
  • I think this is the same answer as [#16877253](https://stackoverflow.com/a/16877253/699665) by [@Shmaperator](https://stackoverflow.com/users/2444035/shmaperator) – MarkHu Jun 08 '18 at 00:27
0

The way to use should still be the toInteger(), because it is not really deprecated.

int value = '99'.toInteger()

The String version is deprecated, but the CharSequence is an Interface that a String implements. So, using a String is ok, because your code will still works even when the method will only work with CharSequence. Same goes for isInteger()

See this question for reference : How to convert a String to CharSequence?

I commented, because the notion of deprecated on this method got me confuse and I want to avoid that for other people.

Maicon Mauricio
  • 2,052
  • 1
  • 13
  • 29
Math Morn
  • 11
  • 2
-1

The Simpler Way Of Converting A String To Integer In Groovy Is As Follows...

String aa="25"
int i= aa.toInteger()

Now "i" Holds The Integer Value.

srinivasan
  • 99
  • 1
  • 4
  • 4
    What does this add to existing answers? The accepted answer posted 9 years ago starts with: "Use the `toInteger()` method to conver... – default locale Aug 02 '18 at 05:33