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/pq27 著作权归作者所有。请勿转载和采集!