0

I try convert string to float because I using Console.ReadLine() for input.

The Console.ReadLine() only accept string values, but I need convert. How I can do that?

Thank you.

Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215
Mesuko
  • 23
  • 1
  • 1
  • 6

5 Answers5

4
        float val = float.Parse(Console.ReadLine());
        Console.WriteLine(val);

OR

        float val2;
        if (!float.TryParse(Console.ReadLine(), out val2))
        {
            Console.WriteLine("Not a valid float");
        }
        else {
            Console.WriteLine(val2);
        }
RSSM
  • 669
  • 7
  • 19
1

Use Convert.ToDouble() to convert the entered string value

double input = Convert.ToDouble(Console.ReadLine())
Rahul
  • 76,197
  • 13
  • 71
  • 125
1

What you can do is use float.TryParse. It should look someone like this.

float fl;
float.TryParse(Console.ReadLine(), out fl);

Although that should work, you can also put use the tryparse in an if statement so that there will be an alert if it does not parse. Like this:

float fl;
if(!float.TryParse(Console.ReadLine(), out fl)){
Console.WriteLine("It didn't parse");
}

This should solve your problem.

J.Tian
  • 231
  • 2
  • 4
  • 11
1

I suggest using double.TryParse in thedo..while loop in order to keep asking until correct value is entered:

 double input = 0.0;

 do { 
   Console.WriteLine("Please enter floating point value");
 }
 while (!double.TryParse(Console.ReadLine(), out input))
Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215
-1
string  User_Text  = Console.ReadLine();
float   User_Float = Convert.ToSingle(User_Text);

This was initially my own question... and this is the answer I found!