NeilGott said:
I have a string formatted such as 5 1/8.
Can someone suggest how to convert this to a double?
Thanks
I would split the string into the three components, whole number, numerator,
denominator. After that, just do the math. How you would handle the third
and fourth items below is up to your mind.
string [] tests = {"5 1/8", "7 3/4", "4 1 9", "12 11/3"};
foreach (string test in tests)
{
if (test.Contains(" ") && test.Contains("/"))
{
string[] words = test.Split(new char[] { ' ', '/' },
StringSplitOptions.RemoveEmptyEntries);
int whole, numerator, denominator;
double value = 0.0;
if (words.Length == 3)
{
if (int.TryParse(words[0], out whole))
if (int.TryParse(words[1], out numerator))
if (int.TryParse(words[2], out denominator))
value = (double)whole
+ ((double)numerator / (double)denominator);
}
else
Console.Out.WriteLine("bad expression");
Console.WriteLine(test + " = " + value.ToString());
}
else Console.WriteLine(test + " is a non-conformant string.");
}