public static Fraction ToFraction(double dValue)
{
try
{
checked
{
Fraction frac;
if (dValue % 1 == 0) // if whole number
{
frac = new Fraction((long)dValue);
}
else
{
double dTemp = dValue;
long iMultiple = 1;
string strTemp = dValue.ToString();
while (strTemp.IndexOf("E") > 0) // if in the form like 12E-9
{
dTemp *= 10;
iMultiple *= 10;
strTemp = dTemp.ToString();
}
int i = 0;
while (strTemp[i] != '.')
i++;
int iDigitsAfterDecimal = strTemp.Length - i - 1;
while (iDigitsAfterDecimal > 0)
{
dTemp *= 10;
iMultiple *= 10;
iDigitsAfterDecimal--;
}
frac = new Fraction((int)Math.Round(dTemp), iMultiple);
}
return frac;
}
}
catch (OverflowException)
{
throw new FractionException("Conversion not possible due to overflow");
}
catch (Exception)
{
throw new FractionException("Conversion not possible");
}
}