如何在Groovy中将String转换为Integer

时间:2016-01-12 06:24:51

标签: groovy

如何在Groovy中将String(这是一个数字)转换为整数。 我使用的是Groovy 2.4.5。这是一个抛出异常的示例代码:

代码:

EXPLAIN EXTENDED
SELECT  o.id, a.first_name, a.last_name, o.total, o.date_created
    FROM  orders o USE INDEX FOR
    JOIN  (PRIMARY)
    JOIN  addresses a ON a.id = o.billing_address_id
    ORDER BY  id DESC
    LIMIT  0, 50 

1   SIMPLE  o   index       PRIMARY 4       50  332632.00   
1   SIMPLE  a   eq_ref  PRIMARY PRIMARY 4   my_basket.o.billing_address_id  1   100.00  

输出(有例外):

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;

1 个答案:

答案 0 :(得分:3)

整数是一个不包含小数点的32位数字。您可能需要 decimal 数据类型,例如Double

试试这个:

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
}