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.
  1. /// <summary>  
  2. ///  return fraction from decimal value  
  3. /// </summary>  
  4. /// <param name="decimalvalue">  
  5. /// <returns>string</returns>  
  6. ///   
  7. /* 
  8.  * logic: 
  9.  * x=5.333 
  10.  * 10x=53.33 
  11.  * 10x-x=Math.Round(53.33-5.333) 
  12.  * 9x=48 
  13.  * x=48/9 
  14.  * find common factor 
  15.  * divide both side by commen factor [ nuerator and denominator] 
  16.  * return faction 
  17.  * */  
  18. string DecimalToFraction(decimal decimalvalue)  
  19. {  
  20.     decimal decimalTemp = decimalvalue;  
  21.     string returnDecimalvalue = string.Empty;  
  22.     decimal temp = decimalTemp * 10;  
  23.     decimal numerator = System.Decimal.Round(temp - decimalTemp);  
  24.     decimal denominator = 10 - 1;  
  25.   
  26.     int comFact = getCommonFactor((int)numerator, (int)denominator);  
  27.     returnDecimalvalue = (numerator / comFact).ToString() + "/" + (denominator / comFact).ToString();  
  28.     return returnDecimalvalue;  
  29. }  
function to find the common factor
  1. private int getCommonFactor(int a, int b)  
  2.         {  
  3.             int count;  
  4.             while (b != 0)  
  5.             {  
  6.                 count = a % b;  
  7.                 a = b;  
  8.                 b = count;  
  9.             }  
  10.             return a;  
  11.         }  
Thanks.

1 comment:

T - eazy said...

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