What is the best way to take a string which can be empty or contain “1.2” for example, and convert it to an integer? int.TryParse fails, of course, and I don’t want to use float.TryParse and then convert to int.
What is the best way to take a string which can be empty or
Share
Solution 1:
Convert.ToDouble(culture-dependent)You may use
Convert.ToDouble. But, beware! The below solution will work only when the number separator in the current culture’s setting is a period character.Solution 2:
Convert.ToDouble(culture-independent)It’s preferable to use
IFormatProviderand convert the number in an independent way from the current culture settings:Solution 3: Parse & Split
Another way to accomplish this task is to use Split on parsed string:
Or:
Notes
IsNullOrEmptycondition.NumberFormatInfo.NumberDecimalSeparatorproperty.Parse,TryParseorConvertclass wisely. Read more at: