// 将字符串转化为数字的几种常见方式
// 1. 使用 Integer.parseInt() 方法将字符串转换为 int 类型
String str1 = "123";
try {
int num1 = Integer.parseInt(str1);
System.out.println("转换后的整数: " + num1); // 输出: 转换后的整数: 123
} catch (NumberFormatException e) {
System.out.println("输入的字符串不是一个有效的整数");
}
// 2. 使用 Integer.valueOf() 方法将字符串转换为 Integer 对象
String str2 = "456";
try {
Integer num2 = Integer.valueOf(str2);
System.out.println("转换后的 Integer 对象: " + num2); // 输出: 转换后的 Integer 对象: 456
} catch (NumberFormatException e) {
System.out.println("输入的字符串不是一个有效的整数");
}
// 3. 使用 Double.parseDouble() 方法将字符串转换为 double 类型
String str3 = "789.01";
try {
double num3 = Double.parseDouble(str3);
System.out.println("转换后的双精度浮点数: " + num3); // 输出: 转换后的双精度浮点数: 789.01
} catch (NumberFormatException e) {
System.out.println("输入的字符串不是一个有效的浮点数");
}
// 4. 使用 BigDecimal(String val) 构造函数将字符串转换为 BigDecimal 对象
import java.math.BigDecimal;
String str4 = "123456789.123456789";
try {
BigDecimal num4 = new BigDecimal(str4);
System.out.println("转换后的 BigDecimal 对象: " + num4); // 输出: 转换后的 BigDecimal 对象: 123456789.123456789
} catch (NumberFormatException e) {
System.out.println("输入的字符串不是一个有效的数字");
}
int 或 Integer。区别在于前者返回的是基本数据类型 int,而后者返回的是包装类 Integer。double 类型。BigDecimal 对象,适用于高精度计算。所有这些方法都可能抛出 NumberFormatException 异常,因此在实际使用时应该用 try-catch 块来捕获异常,以确保程序的健壮性。
上一篇:java aes解密
下一篇:java8 list去重
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站