Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Use the <code>toInteger()</code> method to convert a <code>String</code> to an <code>Integer</code>, e.g.</p> <pre><code>int value = "99".toInteger() </code></pre> <p>An alternative, which avoids using a deprecated method (see below) is</p> <pre><code>int value = "66" as Integer </code></pre> <p>If you need to check whether the <code>String</code> <em>can</em> be converted before performing the conversion, use </p> <pre><code>String number = "66" if (number.isInteger()) { int value = number as Integer } </code></pre> <h2>Grails</h2> <p>If you're converting a request parameter in a Grails controller, there's an even better way</p> <pre><code>Integer paramValue = params.int('paramName') </code></pre> <p>One of the nice features of this technique is that it's safe, i.e. if the parameter cannot be converted to an <code>Integer</code> it returns null rather than throwing an exception.</p> <h2>Deprecation Update</h2> <p>In recent versions of Groovy one of the <code>toInteger()</code> methods has been deprecated. The following is taken from <code>org.codehaus.groovy.runtime.StringGroovyMethods</code> in Groovy 2.4.4</p> <pre><code>/** * 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); } </code></pre> <p>You can force the non-deprecated version of the method to be called using something awful like:</p> <pre><code>int num = ((CharSequence) "66").toInteger() </code></pre> <p>Personally, I much prefer:</p> <pre><code>int num = 66 as Integer </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload