Try splitting it on the space and slash, something like:
double FractionToDouble(string fraction) {
double result;
if(double.TryParse(fraction, out result)) {
return result;
}
string[] split = fraction.Split(new char[] { ' ', '/' });
if(split.Length == 2 || split.Length == 3) {
int a, b;
if(int.TryParse(split[0], out a) && int.TryParse(split[1], out b)) {
if(split.Length == 2) {
return (double)a / b;
}
int c;
if(int.TryParse(split[2], out c)) {
return a + (double)b / c;
}
}
}
throw new FormatException("Not a valid fraction.");
}
Hey, it worked! Remember to check for a division by zero, too. You'll get Infinity, -Infinity, or NaN as a result.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…