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位小数。如下:
但
我应该如何检查呢?
答案 0 :(得分: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
}
答案 1 :(得分:-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!");
}