Reputation: 65
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!");
}
so i have to make sure that the price that will be inputed has and must be 2 decimal places. Such as the following:
but
how should i check for it it?
Upvotes: 3
Views: 5596
Reputation: 123739
Try this:-
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!");
}
Update
Regex Check:-
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
}
Upvotes: 2
Reputation: 846
check inputPrice.Split('.')[1].Length == 2
UPDATE:
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!");
}
Upvotes: -1