Unable to restrict number of decimal digits when p

2019-06-26 02:52发布

问题:

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?

回答1:

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.

   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


回答2:

I've found the solution within stackoverflow:

(Posted by carlosfigueira: C# Check if a decimal has more than 3 decimal places? )

    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;
    }


回答3:

Maybe not so elegant as the other options proposed, but somewhat simpler I think:

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


回答4:

Or you could just do some simple integer math:

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