3

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)
user2650065
  • 31
  • 1
  • 1
  • 3
  • "3.5" is not an integer. number yes, but not integer. double/float maybe? – Igor Artamonov Jan 12 '16 at 06:26
  • 1
    why use both def and String together? `def String a` – Sachin Jan 12 '16 at 08:06
  • My understanding was, a String may be "anything" when it is declared under quotes, a 'decimal point' is also considered as a part of the string. I used 'def' and then 'String' to declare that variable exclusively as a String. Only 'def' may not exclusively declare the type. Please correct me. – user2650065 Jan 12 '16 at 15:12
  • String b = "3.5" was enough def is not required: if you give the type you can omit the def. And of course the period (character '.') is part of the string.But the String class does't know it is a decimal point. – user1708042 Jan 13 '16 at 13:45

1 Answers1

5

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
}
Igor Artamonov
  • 35,450
  • 10
  • 82
  • 113