using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Test1 : MonoBehaviour {
string str1 = "12.222";
string str2 = "123";
string str3 = "abc";
float a;
int b;
void Start () {
if (float.TryParse(str1,out a))
{
a = float.Parse(str1);
Debug.Log(a + 12);
}
else
{
Debug.Log("無法轉換");
}
//float無法轉換爲int
if (int.TryParse(str1, out b))
{
b = int.Parse(str1);
Debug.Log(a + 12);
}
else
{
Debug.Log("無法轉換");
}
//int可以轉成float
if (float.TryParse(str2, out a))
{
a = float.Parse(str2);
Debug.Log(a + 12);
}
else
{
Debug.Log("無法轉換");
}
//字符串無法傳轉換爲int 和 float
if (float.TryParse(str3, out a))
{
a = float.Parse(str3);
Debug.Log(a + 12);
}
else
{
Debug.Log("無法轉換");
}
if (int.TryParse(str3, out b))
{
b = int.Parse(str3);
Debug.Log(a + 12);
}
else
{
Debug.Log("無法轉換");
}
//另一種方式
Debug.Log(Convert.ToSingle(str1));
Debug.Log(Convert.ToInt32(str2));
}
}
結果: