How convert string fraction to Number (ex: 5 1/8) ?

  • Thread starter Thread starter NeilGott
  • Start date Start date
N

NeilGott

I have a string formatted such as 5 1/8.

Can someone suggest how to convert this to a double?

Thanks
 
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.");
}
 
NeilGott said:
I have a string formatted such as 5 1/8.

Can someone suggest how to convert this to a double?

I would find regex tempting:

private static readonly Regex re = new Regex(@"(\d+)
(\d+)/(\d+)", RegexOptions.Compiled);
public static double FractionParse(string s)
{
Match m = re.Match(s);
if(m.Success)
{
return int.Parse(m.Groups[1].Value) +
int.Parse(m.Groups[2].Value) / (double)int.Parse(m.Groups[3].Value);
}
else
{
throw new ArgumentException(s + " is not a valid
fraction");
}
}

Arne
 
Back
Top