[英]C# ReadLine float
I try convert string to float because I using Console.ReadLine()
for input.我尝试将字符串转换为浮点数,因为我使用Console.ReadLine()
进行输入。
The Console.ReadLine()
only accept string values, but I need convert. Console.ReadLine()
只接受字符串值,但我需要转换。 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);
}
使用Convert.ToDouble()
转换输入的字符串值
double input = Convert.ToDouble(Console.ReadLine())
What you can do is use float.TryParse. 您可以使用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. 尽管这应该可行,但是您也可以在if语句中使用tryparse,以便在不解析时发出警报。 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 the do..while
loop in order to keep asking until correct value is entered: 我建议在do..while
循环中使用double.TryParse
,以便不断询问直到输入正确的值:
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!这最初是我自己的问题……这就是我找到的答案!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.