在 C# 中将字符串解析为十进制时无法限制小数位数

Vig*_*esh 5 .net c# parsing decimal

我正在尝试将字符串解析为小数,如果字符串中小数点后的数字超过 2 位,则解析应该失败。

例如:

1.25有效但1.256无效。

我尝试使用decimal.TryParseC# 中的方法按以下方式解决,但这没有帮助...

NumberFormatInfo nfi = new NumberFormatInfo();
nfi.NumberDecimalDigits = 2;
if (!decimal.TryParse(test, NumberStyles.AllowDecimalPoint, nfi, out s))
{
    Console.WriteLine("Failed!");
    return;
}            
Console.WriteLine("Passed");
Run Code Online (Sandbox Code Playgroud)

有什么建议么?

Ale*_*lex 4

看一下Regex。有各种主题涵盖该主题。

示例: 正则表达式匹配 2 位数字,可选小数,两位数字

Regex decimalMatch = new Regex(@"[0-9]?[0-9]?(\.[0-9]?[0-9]$)");这应该适合你的情况。

   var res = decimalMatch.IsMatch("1111.1"); // True
  res = decimalMatch.IsMatch("12111.221"); // False
  res = decimalMatch.IsMatch("11.21"); // True
  res = decimalMatch.IsMatch("11.2111"); // False
  res = decimalMatch.IsMatch("1121211.21143434"); // false
Run Code Online (Sandbox Code Playgroud)