Introduction
Everyone knows that "everything is easy in .NET" and in most cases it really is. This also applies to string parsing issues. When you want to convert string "123.4" into value 123.4, you usually write code looking like:
double someNumber;
string myNumber = "123.4";
try
{
someNumber = double.Parse(myNumber);
}
catch(Exception)
{
}
In most cases it works with no trouble. Until your string is not a number or... decimal separator is different than one defined in your system.
Let's assume that your system decimal separator is a comma (",") and you want to parse string with dot (".") separator - there's no way. An exception is thrown (and you are happy that try-catch works :) ).
There is of course an easy way to parse strings with decimal separator you want to use. The Parse
method allows to define additional parameter - IFormatProvider
. If you put NumberFormatInfo
object as a second parameter of Parse
method, you can specify what decimal separator should be used.
According to MSDN you can obtain current thread NumberFormatInfo
by CurrentInfo
static property. There is some confusion because CurrentInfo
is a read-only property and you would like to modify the decimal separator.
There's a little "walk around" - use current CultureInfo
, "clone" its NumberFormatInfo
and modify the decimal separator:
class ParserClass
{
...
static System.Globalization.NumberFormatInfo ni = null;
public ParserClass()
{
System.Globalization.CultureInfo ci =
System.Globalization.CultureInfo.InstalledUICulture;
ni = (System.Globalization.NumberFormatInfo)
ci.NumberFormat.Clone();
ni.NumberDecimalSeparator = ".";
}
public someMethod()
{
double someNumber;
string myNumber = "123.4";
try
{
someNumber = double.Parse(myNumber,ni);
}
catch(Exception)
{
}
}
}
Using static variable ni
allows you to use it whenever you parse string with "." decimal separator (assuming that instance of ParserClass
is created).