允许'。' (点)仅在控制台中输入数字

时间:2013-08-05 17:11:49

标签: c#

我有一个代码

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

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

2 个答案:

答案 0 :(得分: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");
        }
    }
}

答案 1 :(得分:-1)

 if ((key.KeyChar >= 48 && key.KeyChar <= 57) || key.KeyChar == 46)
   {
         _val += key.KeyChar;
        Console.Write(key.KeyChar);
   }