开发者

Where can i find a .net implementation of atof?

开发者 https://www.devze.com 2022-12-20 04:34 出处:网络
Is there an implementation for the c language\'s atof function in the .net world?float.Parse does not behave the same.

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.


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;
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号