Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR CSHARP

string to float c#

// 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;
    }
Source by stackoverflow.com #
 
PREVIOUS NEXT
Tagged: #string #float
ADD COMMENT
Topic
Name
9+1 =