0

我有一个代码

string _val = "";
Console.Write("Enter your value: ");
ConsoleKeyInfo key;

do
{
    key = Console.ReadKey(true);
    if (key.Key != ConsoleKey.Backspace)
    {
        double val = 0;
        bool _x = double.TryParse(key.KeyChar.ToString(), out val);
        if (_x)
        {
            _val += key.KeyChar;
            Console.Write(key.KeyChar);
        }
    }
    else
    {
        if (key.Key == ConsoleKey.Backspace && _val.Length > 0) 
        {
            _val = _val.Substring(0, (_val.Length - 1));
            Console.Write("\b \b");
        }
    }
}
while (key.Key != ConsoleKey.Enter);

Console.WriteLine();
Console.WriteLine("The Value You entered is : " + _val);

只允许输入数字。但是我怎么能允许一个'.'(点)符号,因为我想使用浮点数?

4

2 回答 2

0
string _val = "";
Console.Write("Enter your value: ");
ConsoleKeyInfo key;
do
{
    key = Console.ReadKey(true);

    if (char.IsNumber(key.KeyChar) || key.KeyChar == '.')
    {
        _val += key.KeyChar;
        Console.Write(key.KeyChar);
    }
    else
    {
        if (key.Key == ConsoleKey.Backspace && _val.Length > 0)
        {
            _val = _val.Substring(0, (_val.Length - 1));
            Console.Write("\b \b");
        }
    }
}
于 2015-03-12T09:24:56.030 回答
-1
 if ((key.KeyChar >= 48 && key.KeyChar <= 57) || key.KeyChar == 46)
   {
         _val += key.KeyChar;
        Console.Write(key.KeyChar);
   }
于 2013-08-05T18:18:57.433 回答