As a matter of fact, I have multiple systems that can generate numeric data and they are stored on some web server in text files. Some of the systems use decimal point as fraction separator, some of the systems use decimal comma as same.
Applications (fat client, .net 2.0) can also be run on either kind of systems.
So after some stumbling I did this: ( http://pastebin.com/vhLXABDD )
public static bool HasDecimalComma;
public static bool HasDecimalPeriod;
public static double GetNumber(string NumberString)
{
if (!HasDecimalComma && !HasDecimalPeriod)
{
string s = string.Format("{0:0.0}", 123.123);
if (s.Contains('.'))
{
HasDecimalPeriod = true;
}
else if (s.Contains(','))
{
HasDecimalComma = true;
}
else
{
throw new SystemException(string.Format("strange number format '{0}'", s));
}
}
if (HasDecimalComma)
{
return double.Parse(NumberString.Replace('.', ','));
}
if (HasDecimalPeriod)
{
return double.Parse(NumberString.Replace(',', '.'));
}
throw new ArgumentException(string.Format("can't parse '{0}'", NumberString));
}
Would you suggest any better, more elegant way?
EDIT:
I am sorry for not mentioning it before, and since your answers lean in that direction - I can't store generating culture with the numbers, I can only try to 'detect' it.
If you are unable to change the call site, and you guarantee that no other kind of separator will be present beside the decimal separator, then you can, more or less use your method. I would suggest
HasDecimalComma
andHasDecimalPeriod
to the body of the method - global state is absolutely not necessary in this case.TryParse
instead ofParse
, because the numbers are expected to be potentially faulty.InvariantCulture
culture (it has a decimal period).So something along these lines:
(Old answer, good in principle, impossible in practice)
I would suggest storing the generating culture along the string, and then using it to call the method, along these lines (using
double.TryParse
):