xxxxxxxxxx
string strValue = "3.14159";
float floatValue;
// using Parse method
floatValue = float.Parse(strValue);
// using TryParse method
if (float.TryParse(strValue, out floatValue))
{
// conversion successful
}
else
{
// conversion failed
}
the Parse method is used to convert the string "3.14159" to a float. The TryParse method is used to convert the string, but it returns a Boolean value indicating whether the conversion was successful or not. The converted float value is stored in the floatValue variable.
xxxxxxxxxx
int integerValue = 42;
float floatValue = (float)integerValue;
Console.WriteLine(floatValue);
xxxxxxxxxx
// This works with both positive and negative numbers
public float stringToFloat(string str)
{
if(str.Length == 0)return 0;
int startIndex = 0;
if(str[0] == '-') startIndex = 1;
int dotIndex = str.Length;
float ans = 0;
for(int i = startIndex; i < str.Length; i++)
{
if(str[i] == '.')
{
dotIndex = i;
break;
}
}
for(int i = startIndex; i < dotIndex; i++)
{
ans += (float)Mathf.Pow(10,dotIndex - i - 1) * (str[i] - '0');
}
for(int i = dotIndex+1; i < str.Length; i++)
{
ans += (float)(str[i] - '0') / Mathf.Pow(10, i - dotIndex);
}
if(startIndex == 1)
ans = -ans;
return ans;
}