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

5
我正在尝试将一个字符串解析为十进制数,如果在字符串中小数点后有超过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");

有什么建议吗?
4个回答

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

谢谢!我也意识到使用正则表达式进行检查是最好的选择,因为我无论如何都要将字符串转换为十进制数。我的正则表达式模式大致如下:".(\d{3})"。由于我只想检查字符串是否有超过3个小数位,所以我想这个模式应该足够了。 - Vignesh
如果您的应用程序需要处理不同的文化,那么它将无法正常工作。 - Tom Carter
好的输入,但是为不同文化设置正则表达式应该不难实现! - Alex

1

我在stackoverflow上找到了解决方案:

(由carlosfigueira发布:C#检查十进制数是否有超过3位小数?)

    static void Main(string[] args)
    {
        NumberFormatInfo nfi = new NumberFormatInfo();
        nfi.NumberDecimalDigits = 2;
        decimal s;
        if (decimal.TryParse("2.01", NumberStyles.AllowDecimalPoint, nfi, out s) && CountDecimalPlaces(s) < 3)
        {
            Console.WriteLine("Passed");
            Console.ReadLine();
            return;
        }
        Console.WriteLine("Failed");
        Console.ReadLine();
    }

    static decimal CountDecimalPlaces(decimal dec)
    {
        int[] bits = Decimal.GetBits(dec);
        int exponent = bits[3] >> 16;
        int result = exponent;
        long lowDecimal = bits[0] | (bits[1] >> 8);
        while ((lowDecimal % 10) == 0)
        {
            result--;
            lowDecimal /= 10;
        }
        return result;
    }

1

也许不像其他提出的选项那样优雅,但我认为有点简单:

        string test= "1,23"; //Change to your locale decimal separator
        decimal num1; decimal num2;
        if(decimal.TryParse(test, out num1) && decimal.TryParse(test, out num2))
        {
            //we FORCE one of the numbers to be rounded to two decimal places
            num1 = Math.Round(num1, 2); 
            if(num1 == num2) //and compare them
            {
                Console.WriteLine("Passed! {0} - {1}", num1, num2);
            }
            else Console.WriteLine("Failed! {0} - {1}", num1, num2);
        }
        Console.ReadLine();

0

或者你可以进行一些简单的整数运算:

class Program
{
    static void Main( string[] args )
    {
        string s1 = "1.25";
        string s2 = "1.256";
        string s3 = "1.2";

        decimal d1 = decimal.Parse( s1 );
        decimal d2 = decimal.Parse( s2 );
        decimal d3 = decimal.Parse( s3 );

        Console.WriteLine( d1 * 100 - (int)( d1 * 100) == 0);
        Console.WriteLine( d2 * 100 - (int)( d2 * 100)  == 0);
        Console.WriteLine( d3 * 100 - (int)( d3 * 100 ) == 0 );
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接