本篇筆記了學習C#時,型別上較常用的轉換方法
明確轉換 (Explicit Converson)
強制將資料轉換成新的資料型別,如果是轉型為int有小數時會直接捨去
變數 = ( cast ) 變數或運算式 ;
ex. y = ( int ) x ;
int x = (int) 5.99; //結果為 5
int x = (int) 3.2; // 結果為 3
Parse 方法
數值型別都會有 Parse 方法,可以使字串轉換成數字型別,若字串內容不是數字則會使程式錯誤
數值變數 = 資料型別.Parse (字串) ;
ex. 將字串str轉換成int
number = int.Parse (str) ;
ex. 將字串str轉換成long
number = long.Parse (str) ;
ex. 將字串str轉換成double
number = double.Parse (str) ;
{
int a = int.Parse ("22"); // 得到數值22
int b = int.Parse ("3.14"); // 得到數值3,因為int沒有小數點
int c = int.Parse ("5.6.7"); // 程式錯誤,因為5.6.7不是數字
double num = double.Parse("3.14") // 得到數值3.14
double num = double.Parse(Console.ReadLine()); // 也可以直接由鍵盤輸入數值
}
ToString、Convert.ToString
上述兩種方法都是把數值轉換成字串
{
int number = 100;
string str = number.ToString();
Console.WriteLine(str); // 輸出str為100
}
{
string str = Convert.ToString(2018); // 數值2018會轉換成字串"2018"
}
除了從數值轉換成字串,也可以帶參數使轉換的字串是貨幣、百分比或者換成其他進制表示
{
int number = 120;
string money = number.ToString("C");
Console.WriteLine(money); // 輸出money為NT$120.00
int number = 120;
string percent = number.ToString("P");
Console.WriteLine(percent); // 輸出percent為12,000.00%
}
Convert 方法
將字串轉換成其他格式
Convert.ToDecimal
Convert.ToDouble
Convert.ToSingle
Convert.ToInt16
Convert.ToInt32
Convert.ToInt64
像Convert.ToInt32而言
如果說 .1 ~ .4 的話會捨去,.6~.9 的話會進位
而 .5 的進位與否,是取決於進位之後,該數是偶數的話就進位,是奇數就捨去
以下面的範例來看,7.5 進位的話為 8,所以就進位,
8.5 進位的話為 9,所以就捨去,
{
int x = Convert.ToInt32(6.1); //結果為 6
int x = Convert.ToInt32(5.5); //結果為 6
int x = Convert.ToInt32(7.9); //結果為 8
int x = Convert.ToInt32(8.2); //結果為 8
int x = Convert.ToInt32(8.5); //結果為 8
int x = Convert.ToInt32(8.9); //結果為 9
}
新人發文,文章敘述如有錯誤及觀念不正確,請不吝嗇指教,感謝~
參考文件
https://docs.microsoft.com/zh-tw/dotnet/api/system.convert?view=netframework-4.7.2
https://docs.microsoft.com/zh-tw/dotnet/csharp/programming-guide/types/casting-and-type-conversions