Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

make sure that input has two decimal place

Tags:

c#

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:

  • 2.00 - correct
  • 3.65 - correct
  • 77.54 - correct
  • 34.12 - correct

but

  • 2 - wrong
  • 2.8 - wrong
  • 2.415 - wrong
  • 99.0 - wrong

how should i check for it it?

like image 670
Mark Miller Avatar asked Nov 30 '25 09:11

Mark Miller


1 Answers

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
}
like image 62
PSL Avatar answered Dec 01 '25 23:12

PSL