Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert a String to an Integer in Groovy [duplicate]

Tags:

groovy

How can I convert a String (which is a number) to integer in Groovy. I am using Groovy 2.4.5. Here is a sample code which throws exception:

Code:

def String a = "CHECK";

def String b = "3.5";
def String c = "7.5";

println "Is a number ? " + a.isNumber();
println "Is b number ? " + b.isNumber();
println "Is c number ? " + c.isNumber();

if (a.equals("CHECK"))
{
    def int x = b.toInteger();
    def int y = c.toInteger();
}

println b+c;

Output (with exceptions):

Is a number ? false
Is b number ? true
Is c number ? true
Exception thrown

java.lang.NumberFormatException: For input string: "3.5"

    at myAdditionLogic.run(myAdditionLogic.groovy:12)
like image 846
user2650065 Avatar asked Dec 03 '25 07:12

user2650065


1 Answers

integer is a 32-bit number that doesn’t include a decimal point. You probably want a decimal data type, like Double.

Try this:

String a = "CHECK";

String b = "3.5";
String c = "7.5";

println "Is a number ? " + a.isNumber();
println "Is b number ? " + b.isNumber();
println "Is c number ? " + c.isNumber();

if (a.equals("CHECK"))
{
    def x = b as Double;
    def y = c as Double;
    println x + y
}
like image 65
Igor Artamonov Avatar answered Dec 05 '25 01:12

Igor Artamonov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!