加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

字符串转数字(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. 字符串中提取数字

两个函数可以帮助我们从字符串中提取数字(整型、浮点型、字符型...)。

  • parseInt()、parseFloat()
  • valueOf()

  String str = "1230";

  int d = Integer.parseInt(str); //静态函数直接通过类名调用

 //or
 int d3 = Integer.valueOf("1230");
 System.out.println("digit3: " + d3);

注意:从字符串中提取可能会产生一种常见的异常:?NumberFormatException。

原因主要有两种:

  • Input string contains non-numeric characters. (比如含有字母"123aB")

  • Value out of range.(比如Byte.parseByte("128") byte的数值范围在 -128~127)

解决方法:

  通过 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 }
View Full Code

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读