It is not possible to limit the number of decimal digits when parsing a string to decimal in C #

I am trying to parse a string to decimal and parsing should fail if there are more than two digits in the string after the decimal point.

eg:

1.25 valid, but 1.256 not valid.

I tried using the decimal.TryParse method in C # to solve as follows, 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?

+4
source share
4 answers

Take a look at Regex . There are various topics dedicated to these subjects.

Example: Regex to match two digits, optional decimal, two digits

Regex decimalMatch = new Regex(@"[0-9]?[0-9]?(\.[0-9]?[0-9]$)"); it should be 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 
+4
source

I found a solution in stackoverflow:

(Submitted by carlosfigueira: C # Check if the decimal point has more than three 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; } 
+1
source

Perhaps not as elegant as the other options, but somewhat simpler:

  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(); 
+1
source

Or you could just do some simple math with an integer:

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

Source: https://habr.com/ru/post/1382841/


All Articles