字符串转数字(with Java)

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

 

你可能感兴趣的:(字符串转数字(with Java))