Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Well, seems I finally had to do it myself. I just had to create a program simulating the natural way I would solve it myself. I just submitted the code to codeproject as writing out the whole code here won't be suitable. You can download the project from here <a href="http://www.codeproject.com/KB/cs/Fraction_Conversion/Frac.zip" rel="nofollow">Fraction_Conversion</a>, or look at <a href="http://www.codeproject.com/Articles/165320/Easy-Way-of-Converting-a-Decimal-to-a-Fraction" rel="nofollow">the codeproject page here</a>.</p> <p>Here's how it works:</p> <ol> <li>Find out whether given decimal is negative</li> <li>Convert decimal to absolute value</li> <li>Get integer part of given decimal</li> <li>Get the decimal part</li> <li>Check whether decimal is recurring. If decimal is recurring, we then return the exact recurring decimal</li> <li>If decimal is not recurring, start reduction by changing numerator to 10^no. of decimal, else we subtract 1 from numerator</li> <li>Then reduce fraction</li> </ol> <p>Code Preview:</p> <pre><code> private static string dec2frac(double dbl) { char neg = ' '; double dblDecimal = dbl; if (dblDecimal == (int) dblDecimal) return dblDecimal.ToString(); //return no if it's not a decimal if (dblDecimal &lt; 0) { dblDecimal = Math.Abs(dblDecimal); neg = '-'; } var whole = (int) Math.Truncate(dblDecimal); string decpart = dblDecimal.ToString().Replace(Math.Truncate(dblDecimal) + ".", ""); double rN = Convert.ToDouble(decpart); double rD = Math.Pow(10, decpart.Length); string rd = recur(decpart); int rel = Convert.ToInt32(rd); if (rel != 0) { rN = rel; rD = (int) Math.Pow(10, rd.Length) - 1; } //just a few prime factors for testing purposes var primes = new[] {41, 43, 37, 31, 29, 23, 19, 17, 13, 11, 7, 5, 3, 2}; foreach (int i in primes) reduceNo(i, ref rD, ref rN); rN = rN + (whole*rD); return string.Format("{0}{1}/{2}", neg, rN, rD); } </code></pre> <p>Thanks @ Darius for given me an idea of how to solve the recurring decimals :)</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload