【程式設計-C#】將字串轉換為數值 Parse (Convert) & TryParse
從視窗文字方塊取得的輸入,雖然"看"起來是數值,本質是字串,需要進一步地將輸入的字串轉換成對應的數值型態,才能進行數值型態的運算(例:加減乘除等…)
Parse方法:
在C#中,每個基本資料型態(char, byte, short, int, long, float, double等)都會對應一個類別型態(Char, Byte, Short, Int32, Long, Float, Double等),提供該數值型態的方法,其中Parse方法是將傳入的字串轉成對應的數值,Parse或Convert方法在轉換字串時,發生問題會產生例外,例如有小數點的字串數值轉換成整數就會發生格式錯誤的例外,此時,你最好寫一個catch補捉例外的區塊,對產生的例外加以處理。
TryParse執行和Parse一樣的功能,不過TryParse發生錯誤時不會拋出例外,回傳一個布林值,成功回傳true,轉型失敗會轉成初始值,並回傳false。
Parse例:
int numVal = Int32.Parse("-105"); Console.WriteLine(numVal); // 輸出: -105TryParse例:
// TryParse 回傳 true,如果轉換是成功的話 // 並且將結果儲存到 j 變數 int j; if (Int32.TryParse("-105", out j)) Console.WriteLine(j); else Console.WriteLine("字串無法解析"); // 輸出: -105Pasre with Try-catch
try { int m = Int32.Parse("abc"); } catch (FormatException e) { Console.WriteLine(e.Message); } // 輸出: Input string was not in a correct format.TryParse例:
string inputString = "abc"; int numValue; bool parsed = Int32.TryParse(inputString, out numValue); if (!parsed) Console.WriteLine("Int32.TryParse 無法轉換 '{0}' 成為一個 int.n", inputString); // 輸出: Int32.TryParse 無法轉換 'abc' 成為一個 int.
資本資料型態:
< div id="scid:812469c5-0cb0-4c63-8c15-c81123a09de7:9f284f2b-369c-4e52-9f90-9cb0e4df8f68" class="wlWriterEditableSmartContent">數值型態 | 數值類別 | 型態 | 寬度 | 數值範圍(bits) |
---|---|---|---|---|
byte | Byte | Unsigned integer | 8 | 0 to 255 |
sbyte | SByte | Signed integer | 8 | -128 to 127 |
int | Int32 | Signed integer | 32 | -2,147,483,648 to 2,147,483,647 |
uint | UInt32 | Unsigned integer | 32 | 0 to 4294967295 |
short | Int16 | Signed integer | 16 | -32,768 to 32,767 |
ushort | UInt16 | Unsigned integer | 16 | 0 to 65535 |
long | Int64 | Signed integer | 64 | -9223372036854775808 to 9223372036854775807 |
ulong | UInt64 | Unsigned integer | 64 | 0 to 18446744073709551615 |
float | Single | Single-precision floating point type | 32 | -3.402823e38 to 3.402823e38 |
double | Double | Double-precision floating point type | 64 | -1.79769313486232e308 to 1.79769313486232e308 |
char | Char | A single Unicode character | 16 | Unicode symbols used in text |
bool | Boolean | Logical Boolean type | 8 | True or false |
object | Object | Base type of all other types | ||
string | String | A sequence of characters | ||
decimal | Decimal | Precise fractional or integral type that can represent decimal numbers with 29 significant digits | 128 | ±1.0 × 10e−28 to ±7.9 × 10e28 |