C#完成將千分位字符串轉換成數字的辦法。本站提示廣大學習愛好者:(C#完成將千分位字符串轉換成數字的辦法)文章只能為提供參考,不一定能成為您想要的結果。以下是C#完成將千分位字符串轉換成數字的辦法正文
本文實例重要完成了C#將千分位字符串轉換成數字的辦法,對C#初學者而言有必定的自創價值,重要內容以下:
重要功效代碼以下:
/// <summary>
/// 將千分位字符串轉換成數字
/// 解釋:將諸如"–111,222,333的千分位"轉換成-111222333數字
/// 若轉換掉敗則前往-1
/// </summary>
/// <param name="thousandthStr">須要轉換的千分位</param>
/// <returns>數字</returns>
public static int ParseThousandthString(this string thousandthStr)
{
int _value = -1;
if (!string.IsNullOrEmpty(thousandthStr))
{
try
{
_value = int.Parse(thousandthStr, NumberStyles.AllowThousands | NumberStyles.AllowDecimalPoint | NumberStyles.AllowLeadingSign);
}
catch (Exception ex)
{
_value = -1;
Debug.WriteLine(string.Format("將千分位字符串{0}轉換成數字異常,緣由:{0}", thousandthStr, ex.Message));
}
}
return _value;
}
單位測試以下:
[TestMethod()]
public void ParseThousandthStringTest()
{
string _thousandthStr = "-111,222,333";
int _expected1 = -111222333;
int _actual1 = StringToolV2.ParseThousandthString(_thousandthStr);
Assert.AreEqual(_expected1, _actual1);
}
感興致的讀者可以本身測試一下,願望對年夜家進修C#有所贊助!