Atof Equivalent in C#

Is it possible to convert this code to C#?


	int pos=0,p=0;
	double v1,expo,res;

	p=value.find("e+");
	
	if(value.find("e+")!=-1 ||value.find("e-")!=-1)
	{
		pos=value.find("e");
		if(atof(value.substr(0,pos).c_str()))
		{
		v1=StringToDouble(value.substr(0,pos));
		expo=StringToDouble(value.substr(pos+1,(value.length()-(pos+1))));
		res=pow(10,expo)*v1;
		return DoubleToString(res);


		}
	}

Open in new window


I saw this online, but wasn't sure how to get the Takewhile function to work.
https://msdn.microsoft.com/en-us/library/system.linq.enumerable.takewhile(v=vs.100).aspx

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

Open in new window

AlHal2Asked:
Who is Participating?
 
it_saigeConnect With a Mentor DeveloperCommented:
In C#, we use the inbuilt Convert Methods, e.g. -
using System;

namespace EE_Q29069400
{
    class Program
    {
        static void Main(string[] args)
        {
            string factorial = "7.1099859e+74";
            double converted = Convert.ToDouble(factorial);
            Console.WriteLine($"Converted string - {factorial}; to Double - {converted}");
            Console.ReadLine();
        }
    }
}

Open in new window

You can also use the type specific Parse and/or TryParse methods; e.g. -
using System;

namespace EE_Q29069400
{
    class Program
    {
        static void Main(string[] args)
        {
            string factorial = "7.1099859e+74";
            double converted;
            if (double.TryParse(factorial, out converted))
            {
                Console.WriteLine($"Converted string - {factorial}; to Double - {converted}");
            }
            else
            {
                Console.WriteLine($"Could not convert {factorial}");
            }
            Console.ReadLine();
        }
    }
}

Open in new window


Each of the preceeding produce the following output -Capture.PNG
-saige-
0
 
AlHal2Author Commented:
Thanks.
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.