Converting a string to int in Groovy

前端 未结 13 2243
陌清茗
陌清茗 2020-11-30 18:45

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.pars

相关标签:
13条回答
  • 2020-11-30 19:13

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

    def strnumber = "100"
    def intValue = strnumber.isInteger() ?  (strnumber as int) : null
    
    0 讨论(0)
  • 2020-11-30 19:14

    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
    
    0 讨论(0)
  • 2020-11-30 19:15

    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.

    0 讨论(0)
  • 2020-11-30 19:16

    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
    
    0 讨论(0)
  • 2020-11-30 19:20
    def str = "32"
    
    int num = str as Integer
    
    0 讨论(0)
  • 2020-11-30 19:29

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

    def number = '123' as int
    
    0 讨论(0)
提交回复
热议问题