Converting a string to int in Groovy

前端 未结 13 2255
陌清茗
陌清茗 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: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.

提交回复
热议问题