groovy 字符串转数据
在Groovy中,可以使用toInteger()、toDouble()、toFloat()等方法将字符串转换为对应的数据类型。
以下是几个示例:
- 将字符串转换为整数:
String str = "123"
int num = str.toInteger()
- 将字符串转换为浮点数:
String str = "3.14"
double num = str.toDouble()
- 将字符串转换为布尔值:
String str = "true"
boolean flag = str.toBoolean()
注意:如果字符串不能转换为对应的数据类型,会抛出异常。因此,在进行转换之前,最好先进行合法性验证,以确保字符串可以成功转换为目标数据类型。
原文地址: https://www.cveoy.top/t/topic/hHYc 著作权归作者所有。请勿转载和采集!