我正在尝试将字符串解析为小数,如果字符串中的小数点后有超过 2 位数字,则解析应该会失败。
例如:
1.25
有效,但 1.256
无效。
我尝试使用 C# 中的 decimal.TryParse
方法以下列方式解决,但这没有帮助...
NumberFormatInfo nfi = new NumberFormatInfo();
nfi.NumberDecimalDigits = 2;
if (!decimal.TryParse(test, NumberStyles.AllowDecimalPoint, nfi, out s))
{
Console.WriteLine("Failed!");
return;
}
Console.WriteLine("Passed");
有什么建议吗?
最佳答案
看看 Regex
。有各种线程涵盖这个主题。
例子: Regex to match 2 digits, optional decimal, two digits
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
关于c# - 在 C# 中将字符串解析为十进制时无法限制小数位数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8253819/