C# Strict Int/Float parsing
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!
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.
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);
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.
精彩评论