|
|
|
|
|
今天在做項目的時候,遇到Parse
小數(shù)拋出異常,提示FormatException:輸入字符串的格式不正確。意思很明確,就是Parse
不能用于小數(shù)轉換,哪怕是小數(shù)點后面為0,例如100.00這樣的數(shù)據(jù)格式。
遇到這個問題,我們可以有兩種解決方法,一種是使用try{}catch(){}
方法,另一種是使用TryParse
代替Parse
方法。
使用try{}catch(){}方法
這個方法比較傳統(tǒng),是任何程序預防拋出錯誤的普遍做法。
示例
try {
int.Parse("100.00");
}
catch (Exception ex) {
Response.Write(ex.Message .ToString ());
}
輸出
輸入字符串的格式不正確。
我們可以根據(jù)catch
的錯誤信息,或者有無catch
錯誤,來判斷程序是否執(zhí)行成功,從而執(zhí)行后面的程序語句。
使用TryParse方法
使用try{}catch(){}
方法雖然能解決問題,但總覺得這樣處理一個字符串轉換數(shù)字不是最理想的方法。其實,我們有C#內(nèi)置的方法來專門處理這個事情,那就是TryParse
方法。
繼續(xù)用上面的數(shù)據(jù),使用TryParse
方法這樣處理。
string numberStr = "100.00";
int number;
bool isParsable = Int32.TryParse(numberStr, out number);
if (isParsable)
Response.Write (number);
else
Response.Write ("不能解析");
TryParse
有兩個功能,當解析成功時就直接返回轉換值,當解析失敗時就返回一個布爾值(true 或 false),可謂一舉兩得,是字符串轉換為 Int 的最安全方法。
了解TryParse方法
在字符串轉換為int的方法中,TryParse
方法無疑是最好用的,如果你對此方法還了解得不夠深入,那么看看下面的介紹。
將數(shù)字的字符串表示形式轉換為其等效的 32 位有符號整數(shù)。返回值指示轉換是否成功。
public static bool TryParse (string? s, out int result);
s
String:要轉換的數(shù)字的字符串。result
Int32:當此方法返回時,如果轉換成功,則包含與s
中包含的數(shù)字等效的 32 位有符號整數(shù)值,如果轉換失敗,則返回零。如果s
參數(shù)為null或Empty、格式不正確或表示小于MinValue或大于MaxValue的數(shù)字,則轉換失敗。此參數(shù)未初始化傳遞;最初提供的任何值result
都將被覆蓋。s
轉換成功;否則,false。下面的示例使用許多不同的字符串值調(diào)用Int32.TryParse(String, Int32)
方法。
using System;
public class Example
{
public static void Main()
{
string[] values = { null, "160519", "9432.0", "16,667",
" -322 ", "+4302", "(100);", "01FA" };
foreach (var value in values)
{
int number;
bool success = int.TryParse(value, out number);
if (success)
{
Console.WriteLine($"Converted '{value}' to {number}.");
}
else
{
Console.WriteLine($"Attempted conversion of '{value ?? "<null>"}' failed.");
}
}
}
}
// The example displays the following output:
// Attempted conversion of '<null>' failed.
// Converted '160519' to 160519.
// Attempted conversion of '9432.0' failed.
// Attempted conversion of '16,667' failed.
// Converted ' -322 ' to -322.
// Converted '+4302' to 4302.
// Attempted conversion of '(100);' failed.
// Attempted conversion of '01FA' failed.
TryParse(String, Int32)
方法在此示例中無法轉換的一些字符串是:
NumberFormatInfo.NegativeSign
和NumberFormatInfo.NumberNegativePattern
屬性定義的負號之外的負號。TryParse
方法與Parse
方法類似,只是TryParse
方法在轉換失敗時不會拋出異常。它消除了在s
無效且無法成功解析的事件中使用異常處理來測試FormatException
的需要。
s
參數(shù)包含多個形式:
[ws][sign]digits[ws]
方括號([ 和 ])中的項目是可選的。下表描述了每個元素。
元素 | 描述 |
---|---|
ws | 可選的空白。 |
sign | 可選標志。 |
digits | 從 0 到 9 的數(shù)字序列。 |
s
參數(shù)使用NumberStyles.Integer
樣式進行解釋。除了十進制數(shù)字,只允許前導和尾隨空格以及前導符號。要顯式定義樣式元素以及可以出現(xiàn)在s
中的文化特定格式信息,請使用Int32.TryParse(String, NumberStyles, IFormatProvider, Int32)
方法,請看文章詳解C# TryParse怎樣轉換小數(shù)、16進制、千分位數(shù)字等字符串。
TryParse
方法的這種重載將s
參數(shù)中的所有數(shù)字解釋為十進制數(shù)字。要解析十六進制數(shù)字的字符串表示,請調(diào)用Int32.TryParse(String, NumberStyles, IFormatProvider, Int32)
重載,請看文章詳解C# TryParse怎樣轉換小數(shù)、16進制、千分位數(shù)字等字符串。
總結
本文介紹了C# Parse
小數(shù)提示FormatException:輸入字符串的格式不正確的原因及解決方法,以及深入介紹了TryParse
方法的用法。