简体   繁体   English

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

[英]Unable to restrict number of decimal digits when parsing a string to decimal in C#

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. 我正在尝试将字符串解析为十进制,如果字符串中的小数点后面有超过2位数,则解析应该失败。

eg: 例如:

1.25 is valid but 1.256 is invalid. 1.25有效但1.256无效。

I tried to use the decimal.TryParse method in C# to solve in the following manner but this does not help... 我尝试在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");

Any suggestions? 有什么建议?

Have a look at Regex . 看看正则Regex There are various threads covering this subjects. 这个主题有各种各样的主题。

example: Regex to match 2 digits, optional decimal, two digits 示例:正则表达式匹配2位数,可选的十进制数,两位数

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

I've found the solution within stackoverflow: 我在stackoverflow中找到了解决方案:

(Posted by carlosfigueira: C# Check if a decimal has more than 3 decimal places? ) (发布者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;
    }

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM