C# 各種類型轉換


基本上是同樣道理

int testInt;
string testString;
double testDouble;

void Test()
{
    //int轉string
    testString = testInt.ToString();
    //string轉int
    testInt = Convert.ToInt32(testString);
    testInt = int.Parse(testString);
    //double轉int
    testInt = (int)testDouble;
}

這邊記一下Convert.ToInt32()和int.Parse()的差別

  • int.Parse()不能處理null值或是非整數(ex:1.5)
  • Convert.ToInt32()遇到null則是會回傳0,遇到小數則是四捨六入(五的話奇數進偶數不進)

另外數字轉字串有特殊用法

int testInt = 12;
float testFloat = 0.34;
string testString;

void Test()
{
    string testString  = testInt.toString("000");//Print "012"
    string testString  = testFloat.toString("#.00");//Print ".34"
}

簡單來說#字號就是有數字才填入,而0就算沒有到那個位數也會自動補齊

#C# #Winform







你可能感興趣的文章

Day 107

Day 107

同步 & 非同步(4) - async & await

同步 & 非同步(4) - async & await

Modelsim 基礎教學

Modelsim 基礎教學






留言討論