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.
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.
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);
}
Use Convert.ToDouble()
to convert the entered string value
double input = Convert.ToDouble(Console.ReadLine())
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.
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))
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!