确保输入有两位小数
本文关键字:两位 小数 输入 确保 | 更新日期: 2023-09-27 18:12:17
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.00 -正确
- 3.65 -修正
- 77.54 -正确
- 34.12 -正确
,
- 2 -错误
- 2.8 -错误
- 2.415 -错误
- 99.0 -错误
我该如何检查它?
试试这个:-
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
}
check 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!");
}