tags:

views:

83

answers:

3

I'm wondering how to implement strict parsing of a string in C#.

Specifically, I want to require that the string contains just the number (in culture-specific format), and no other characters.

"1.0"  -> 1.0  
"1.5 " -> fail  
" 1.5" -> fail  
" 1,5" -> fail (if culture is with ".")  
"1,5"  -> fail  

Cheers!

+4  A: 

The Int32.Parse method accepts flags covering certain situations you mention. Have look into MSDN here on NumberStyles enumeration. Also, it accepts culture-specific formatting information.

Ondrej Tucny
Or in this specific example, Float.Parse or Decimal.Parse. Any of those methods will accept an IFormatProvider object. You should be able to pass System.Globalization.CultureInfo.CurrentUICulture.NumberFormat right into Parse. Not sure about the white spaces, it may automatically trim. Not sure why that would be a problem, but it ain't my program. =)
Chuck
`NumberStyles` is exactly what provides support for (dis)allowing trailing/leading whitespace.
Ondrej Tucny
+2  A: 

Check out the Parse/TryParse methods of the int, float and double types. They have overloads that allow specifying a CultureInfo and allow restricting the accepted number format:

string value = "1345,978";
NumberStyles style = NumberStyles.AllowDecimalPoint;
CultureInfo culture = CultureInfo.CreateSpecificCulture("fr-FR");
double number;

if (double.TryParse(value, style, culture, out number))
   Console.WriteLine("Converted '{0}' to {1}.", value, number);
else
   Console.WriteLine("Unable to convert '{0}'.", value);
0xA3
A: 

TryParse specifically allows whitespace before and after the number Double.TryParse reference, so it is not strict enough for your requirements unless you explicitly use NumberStyles.

smirkingman