I’m trying to parse a string to a decimal and the parsing should failed if there are more than 2 digits after the decimal point in the string.
e.g:
1.25 is valid but 1.256 is invalid.
I tried to use the decimal.TryParse method in C# to solve in the following manner but this does not help…
NumberFormatInfo nfi = new NumberFormatInfo();
nfi.NumberDecimalDigits = 2;
if (!decimal.TryParse(test, NumberStyles.AllowDecimalPoint, nfi, out s))
{
Console.WriteLine("Failed!");
return;
}
Console.WriteLine("Passed");
Any suggestions?
Have a look at
Regex. There are various threads covering this subjects.example:
Regex to match 2 digits, optional decimal, two digits
Regex decimalMatch = new Regex(@"[0-9]?[0-9]?(\.[0-9]?[0-9]$)");this should do in your case.