tags:

views:

95

answers:

1

Is there an implementation for the c language's atof function in the .net world? float.Parse does not behave the same.

Some behavioral differences.

  • "50 Apple" will return 50.
  • "50 Apple. 1" will return 50.
  • "Apple" will return 0.
+7  A: 

If you mean you want to duplicate atof's leniency (ignoring preceding whitespace and trailing non-numeric characters), you can do this (assuming C# 3.0):

float myAtof(string myString)
{
    Predicate<char> testChar = c => c == '.' || 
                                    c == '-' || 
                                    c == '+' || 
                                    char.IsDigit(c);

    myString = new string(myString.Trim().TakeWhile(testChar).ToArray());

    if (myString.Length > 0)
    {
        float rvl;

        // accounts for bogus strings of valid chars, e.g. ".-":
        if (float.TryParse(myString, out rvl))
        {
            return rvl;
        }
    }

    return 0;
}
Ben M