字符串轉數字(with Java)


1. 字符串中提取數字

兩個函數可以幫助我們從字符串中提取數字(整型、浮點型、字符型...)。

  • parseInt()、parseFloat()...
  • valueOf() 
  String str = "1230";
    int d = Integer.parseInt(str); //靜態函數直接通過類名調用,返回int型
 //or
 int d3 = Integer.valueOf("1230"); //通過靜態函數valueOf返回包裝類Integer類型
 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 提前捕捉潛在異常。

 try {
              float d2 = Float.parseFloat(str);
              System.out.printf("digit2: %.2f ", d2 );
          } catch (NumberFormatException e){
              System.out.println("Non-numerical string only.");
      }
  
try {
             byte d4 = Byte.parseByte(str);
             System.out.println("digit3: " + d4);
         } catch (NumberFormatException e) {
             System.out.println("\nValue out of range. It can not convert to digits.");
         }            

2. 數字轉字符串

使用 String 類的 valueOf() 函數

 String s = String.valueOf(d); 

3. 代碼

public class StringToDigit {
    public static void main(String[] args) {

        //convert string to digits using parseInt()、parseFloat()...
        String str = "127";
        int d = Integer.parseInt(str);
        System.out.printf("d: %d ", d);

        try {
            float d2 = Float.parseFloat(str);
            System.out.printf("digit2: %.2f ", d2 );
        } catch (NumberFormatException e){
            System.out.println("Non-numerical string only.");
        }
     

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

        try {
            byte d4 = Byte.parseByte(str);
            System.out.println("digit3: " + d4);
        } catch (NumberFormatException e) {
            System.out.println("\nValue out of range. It can not convert to digits.");
        }

        //convert digits to string using valueOf()
        System.out.println(String.valueOf(d));
        System.out.println(String.valueOf(d3));
    }
}

  

 加油各位!如果覺得有用的話,可以點個推薦嗎?(祈求臉.jpg) 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM