在C#中将字符串解析为十进制时,无法限制小数位数 [英] Unable to restrict number of decimal digits when parsing a string to decimal in C#

查看:93
本文介绍了在C#中将字符串解析为十进制时,无法限制小数位数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将字符串解析为十进制,并且如果字符串中小数点后的位数超过2位,则解析应该会失败.

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.

例如:

1.25有效,但1.256无效.

我试图在C#中使用decimal.TryParse方法以以下方式解决问题,但这无济于事...

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");

有什么建议吗?

推荐答案

看看Regex.有许多主题涉及这个主题.

Have a look at Regex. There are various threads covering this subjects.

示例: 用于匹配2位,可选的十进制,两位数的正则表达式

Regex decimalMatch = new Regex(@"[0-9]?[0-9]?(\.[0-9]?[0-9]$)");这应该针对您的情况.

Regex decimalMatch = new Regex(@"[0-9]?[0-9]?(\.[0-9]?[0-9]$)"); this should do in your case.

   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#中将字符串解析为十进制时,无法限制小数位数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆