0
Console.Write("Input price: ");
double price;
string inputPrice = Console.ReadLine();
if (double.TryParse(inputPrice, out price))
{
    price = double.Parse(inputPrice);
}
else
{
    Console.WriteLine("Inventory code is invalid!");
}

所以我必须确保输入的价格必须是小数点后 2 位。如下所示:

  • 2.00 - 正确
  • 3.65 - 正确
  • 77.54 - 正确
  • 34.12 - 正确

  • 2 - 错误
  • 2.8 - 错误
  • 2.415 - 错误
  • 99.0 - 错误

我应该如何检查它?

4

2 回答 2

2

试试这个:-

Console.Write("Input price: ");
double price;
string inputPrice = Console.ReadLine();
var num = Decimal.Parse(inputPrice); //Use tryParse here for safety
if (decimal.Round(num , 2) == num)
{
   //You pass condition
}
else
{
    Console.WriteLine("Inventory code is invalid!");
}

更新

正则表达式检查:-

var regex = new Regex(@"^\d+\.\d{2}?$"); // ^\d+(\.|\,)\d{2}?$ use this incase your dec separator can be comma or decimal.
var flg = regex.IsMatch(inputPrice);
if(flg)
{
\\its a pass
}
else
{
\\failed
}
于 2013-05-04T03:51:51.553 回答
-1

查看inputPrice.Split('.')[1].Length == 2

更新:

Console.Write("Input price: ");
            double price;
            string inputPrice = Console.ReadLine();
            if (double.TryParse(inputPrice, out price) && inputPrice.Split('.').Length == 2 && inputPrice.Split('.')[1].Length == 2)
            {
                price = double.Parse(inputPrice);
            }
            else
            {
                Console.WriteLine("Inventory code is invalid!");
            }
于 2013-05-04T03:46:34.083 回答