Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Int32.TryParse with multiple group separators

Tags:

c#

.net

I'm trying to create a method that can handle and validate integers as on ok input. The issue is our requirements which states the following numbers as an ok input regardless of chosen language:

1500, 1.500, 1,500, 1 500
-1500, -1.500, -1,500, -1 500
1500000, 1.500.500, 1,500,500 1 500 500
-1500000, -1.500.500, -1,500,500 -1 500 500

and so on.

My method now looks like this:

private bool TryParseInteger(string controlValue, out int controlInt)
{
      int number;
      NumberStyles styles = NumberStyles.Integer | NumberStyles.AllowThousands;

      bool result = Int32.TryParse(controlValue, styles,
            CultureInfo.InvariantCulture, out number);
      controlInt = number;

      return result;
}

This does not work as I want it to. 1.500 and 1.500.500 is not validated as a correct input.

Is there another way to approach this?

Thanks for all the help. As it turns out 1.500,50 (and so on) should not pass validation which makes the suggested solutions not work. Any other ideas?

like image 492
user3351548 Avatar asked Feb 25 '14 14:02

user3351548


People also ask

What is Int32 TryParse?

TryParse(String, Int32) Converts the string representation of a number to its 32-bit signed integer equivalent. A return value indicates whether the conversion succeeded.

What is TryParse C #?

TryParse is . NET C# method that allows you to try and parse a string into a specified type. It returns a boolean value indicating whether the conversion was successful or not. If conversion succeeded, the method will return true and the converted value will be assigned to the output parameter.

What does TryParse return on failure?

TryParse method converts a string value to a corresponding 32-bit signed integer value data type. It returns a Boolean value True , if conversion successful and False , if conversion failed.


1 Answers

Just replace all those signs!

This code:

string[] arr = new[] { "1500", "1.500", "1,500", "1 500", "-1500", "-1.500", "-1,500", "-1 500",
                                "1500000", "1.500.500", "1,500,500","1 500 500",
                                "-1500000", "-1.500.500", "-1,500,500","-1 500 500"};

foreach (var s in arr)
{
    int i = int.Parse(s.Replace(" ", "").Replace(",", "").Replace(".", ""));

    Console.WriteLine(i);
}

Produces:

1500

1500

1500

1500

-1500

-1500

-1500

-1500

1500000

1500500

1500500

1500500

-1500000

-1500500

-1500500

-1500500

like image 184
astef Avatar answered Nov 13 '22 02:11

astef