Click here to check my latest exciting videos on youtube
Search Mallstuffs

Flag Counter
Spirituality, Knowledge and Entertainment


Locations of visitors to this page


Latest Articles


Move to top
Converting Fraction into decimal
Posted By Sarin on Dec 25, 2012     RSS Feeds     Latest Hinduism news
2709 Views

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.
  
Note: Images used on this website are either a production of Bhaktivedanta Book Trust(https://www.krishna.com), Iskcon Foundation or were found in google search under "Free to use and share". If any of the images presented here violates copyright issues or infringes anyone copyright or are not under "Fair use", then please bring it to our notice. Read Disclaimer for more.

Share this to your friends. One of your friend is waiting for your share.
Related Articles
Silverlight New features & system requirement
What is Silverlight,its features and how it works
Show animation effects using ajax UpdatePanelAnimation control
Converting Fraction into decimal
Easiest Way of logging in .Net

Post Comment