字符串转数字(with Java)
发布时间:2020-12-15 07:32:44 所属栏目:Java 来源:网络整理
导读:1. 字符串中提取数字 两个函数可以帮助我们从字符串中提取数字(整型、浮点型、字符型...)。 parseInt()、parseFloat() valueOf() String str = "1230" ; int d = Integer.parseInt(str); //静态函数直接通过类名调用 // or int d3 = Integer.valueOf("1230
1. 字符串中提取数字两个函数可以帮助我们从字符串中提取数字(整型、浮点型、字符型...)。
String str = "1230"; int d = Integer.parseInt(str); //静态函数直接通过类名调用 //or int d3 = Integer.valueOf("1230"); System.out.println("digit3: " + d3); 注意:从字符串中提取可能会产生一种常见的异常:?NumberFormatException。原因主要有两种:
解决方法:通过 try-catch-block 提前捕捉潜在异常。1 try { 2 float d2 = Float.parseFloat(str); 3 System.out.printf("digit2: %.2f ",d2 ); 4 } catch (NumberFormatException e){ 5 System.out.println("Non-numerical string only."); 6 } 7 8 try { 9 byte d4 = Byte.parseByte(str); 10 System.out.println("digit3: " + d4); 11 } catch (NumberFormatException e) { 12 System.out.println("nValue out of range. It can not convert to digits."); 13 } ? ? 2. 数字转字符串使用String类的valueOf()函数 String s = String.valueOf(d); ? 3. 代码1 public class StringToDigit { 2 public static void main(String[] args) { 3 4 //convert string to digits using parseInt()、parseFloat()... 5 String str = "127"; 6 int d = Integer.parseInt(str); 7 System.out.printf("d: %d ",d); 8 9 try { 10 float d2 = Float.parseFloat(str); 11 System.out.printf("digit2: %.2f ",d2 ); 12 } catch (NumberFormatException e){ 13 System.out.println("Non-numerical string only."); 14 } 15 16 17 //or using valueOf() 18 int d3 = Integer.valueOf("1230"); 19 System.out.println("digit3: " + d3); 20 21 try { 22 byte d4 = Byte.parseByte(str); 23 System.out.println("digit3: " + d4); 24 } catch (NumberFormatException e) { 25 System.out.println("nValue out of range. It can not convert to digits."); 26 } 27 28 //convert digits to string using valueOf() 29 System.out.println(String.valueOf(d)); 30 System.out.println(String.valueOf(d3)); 31 } 32 } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
相关内容
- Java泛型参数界定到任何一个类型的范围
- springboot中filter的用法详解
- Java Generic:Generic可以扩展另一个Generic类吗?
- java – 在WebSphere 8.5中查找JDBC DataSource
- 什么是java中的@deprecated反向
- java中快速创建带初始值的List和Map实例
- java – 使用BouncyCastle从文件中读取椭圆曲线私钥
- java:在一个webapp中使用同一个lib的两个版本
- java – Jackson – 将boolean序列化为1/0而不是true / fal
- java – AndEngine – 无法实例化Activity