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?
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With