Adsence750x90

Sunday, August 12, 2012

Decimal to fraction convertion c#

I think there is nothing to explain below code. I used this code snippet to calculate the fractional value of a decimal number. Might help someone.
        /// 
        ///  return fraction from decimal value
        /// 
        /// 
        /// string
        /// 
        /*
         * logic:
         * x=5.333
         * 10x=53.33
         * 10x-x=Math.Round(53.33-5.333)
         * 9x=48
         * x=48/9
         * find common factor
         * divide both side by commen factor [ nuerator and denominator]
         * return faction
         * */
 public string DecimalToFraction(decimal decimalvalue)
        {
            decimal decimalTemp = decimalvalue;
            string returnDecimalvalue = string.Empty;
            decimal temp = decimalTemp * 10;
            decimal numerator = System.Decimal.Round(temp - decimalTemp);
            decimal denominator = 10 - 1;

            int comFact = getCommonFactor((int)numerator, (int)denominator);
            returnDecimalvalue = (numerator / comFact).ToString() + "/" + (denominator / comFact).ToString();
            return returnDecimalvalue;
        }


 
function to find the common factor
private int getCommonFactor(int a, int b)
        {
            int count;
            while (b != 0)
            {
                count = a % b;
                a = b;
                b = count;
            }
            return a;
        }
Thanks.

1 comment:

T - eazy said...

This doesn't work, the denominator is always 9 in this case when searching for a common factor