Converting Fraction into decimal
Recently, While working on an application, I came across a need of converting fraction into decimal.Actually, I was expecting the .Net framework to automatically convert the string in the format ½ when I use the convert.ToDecimal function. For example, in the below screenshot, I tried to convert the fraction into decimal using the convert to decimal function. But this does not work. On running the application, I got the error as shown below
So, I felt the need of writing my own function for converting fractions into decimal. I came up with the following function to achieve this functionality.
public static decimal FractionToDecimal(String input)
{
String[] fraction = input.Split(new[] "/" , StringSplitOptions.RemoveEmptyEntries);
if (fraction.Length > 2)
{
throw new ArgumentOutOfRangeException();
}
if (fraction.Length == 1)
return Convert.ToDecimal(fraction[0]);
Int32 numerator, denominator;
if (Int32.TryParse(fraction[0], out numerator) && Int32.TryParse(fraction[1], out denominator))
{
if (denominator == 0)
{
throw new InvalidOperationException("Divide by 0 occurred");
}
return (decimal)numerator / denominator;
}
throw new ArgumentException();
}
I splitted the string into numerator and denominator and then used the simple division operation to divide numerator by denominator to get the desired result. In addition to this, I have handled the exceptions to handle wrong or incorrect input string.
For a demo, I have created a simple console application accepting a single input.
As shown below, I entered 1/5 as input and got 0.2 as the decimal output. Hope this help you in your programming.