Parsing strings for numbers in the .NET Micro Framework

18 06 2007
During one of my last .NET Micro Framework courses we ran into an interesting problem. We wanted to parse a string containing an integer such as "15" to get the integer value 15.
This normally can be done easily in the .NET Framework using the corresponding methods Int32.Parse or the Convert.ToInt32 methods of those framework classes. The bad thing is, that these methods are currently missing in the .NET Micro Framework versions of Int32 and Convert. According to Microsoft, this is kind of a mishap and will be fixed in future releases.
Until then You can use this workaround:

public static bool TryParseFloat(string s, out float result)
    bool success = true;
    int decimalDiv = 0;
    result = 0;
        for (int i = 0; i < s.Length; i++)
            if (s[i] == ‘.’ && decimalDiv == 0)
                decimalDiv = 1;
            else if (s[i] < ‘0’ || s[i] > ‘9’)
                success = false;
                result = result * 10;
                decimalDiv = decimalDiv * 10;
                result += (int)(s[i] – ‘0’);
        if (decimalDiv > 0) result = (float) result / decimalDiv; //Avoid devision by zero
        success = false;
    return success;


This routine will give you back a float value for your string, that can then be casted, e.g. into an integer. 








Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: