Jan
18
2006
Safer ToDouble
Posted by admin under
.NET
While this hardly can be considered rocket science it's a real timesaver for me. As a consultant I am often challenged with dealing with data from different sources, such as textfiles from AS/400, screen input from users running OS of different languages; simply giving me different formats of what should be the same ddata. One example is a double (float) value:
Sometimes you get them with a dot (.) as delimiter and sometimes with a comma (,). And that can't be handled by Convert.ToDouble() since it uses the current local settings.
I instead uses this function, which I have put in a textutils dll:
public static double ToDouble(string sTxt) {
sTxt = sTxt.Trim();
if ( sTxt == "" )
return 0;
double dRet;
bool fOK = true;
try
{
dRet = Convert.ToDouble(sTxt);
}
catch
{
fOK = false;
}
if ( !fOK )
{
try
{
string sTemp = sTxt.Replace(",",".");
dRet = Convert.ToDouble(sTemp);
}
catch
{
}
}
if ( !fOK )
{
try
{
string sTemp = sTxt.Replace(".",",");
dRet = Convert.ToDouble(sTemp);
} catch
{
}
}
return dRet;
}