In this post, I am going to show you different ways to
convert string to an integer.
a.
Using toInteger method
b.
Using as operator
c.
Using Integer.valueOf method
d.
Using Integer.parseInt method
Groovy string provides ‘isInteger’ method, it returns
true, if the string can be converted to integer, else false.
HelloWorld.groovy
String data1 = "123" String data2 = "Hello123" convertToInt(data1) convertToInt(data2) void convertToInt(String data){ if(data.isInteger()){ int result1 = data.toInteger() int result2 = data as Integer int result3 = Integer.parseInt(data) int result4 = Integer.valueOf(data) println "result1: $result1" println "result2: $result2" println "result3: $result3" println "result4: $result4" }else{ println "$data can't be converted to integer" } }
Output
result1: 123
result2: 123
result3: 123
result4: 123
Hello123 can't be converted to integer
Hello123 can't be converted to integer
No comments:
Post a Comment