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)
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With