數字轉字串是非常常用的功能
這篇就介紹primitive type, wrapper class與String轉換的方法
1. 官網https://docs.oracle.com/javase/tutorial/java/data/numberclasses.html
2. 以下就列出一些轉換方法, 以Integer為例
a. 字串轉數值(基本是轉成wrapper class, 由於autobox的關係, 會直接轉成primitive type)
語法: class名稱.decode(字串數值)
ex: Integer.decode("010");
b. 字串轉數值, 限制10進位
語法: class名稱.parseInt(字串數值)
ex: Integer.parseInt("123");
c. 字串轉數值, 可選擇進位方式
語法: class名稱.parseInt(字串數值, 進位方式)
ex: Integer.parseInt("0101", 2);
d. class值轉字串
語法: class值.toString()
ex: new Integer(100).toString()
e. class值轉字串
語法: class名稱.toString(數字)
ex: Integer.toString(100)
f. 將目標資料型態的數字轉成對應wrapper class
語法: class名稱.value(數字)
ex: Integer.value(100)
g. 將目標字串數字轉成對應wrapper class
語法: class名稱.value(字串數字)
ex: Integer.value("100")
g. 將目標字串數字選擇進位方式轉成對應wrapper class
語法: class名稱.value(字串數字, 進位方式)
ex: Integer.value("100", 2)