Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

About this user

Michelle

« Newer Snippets
Older Snippets »
Showing 1-1 of 1 total  RSS 

Decimal to fraction in Ruby

// Adds a 'to_fraction' method to Float. Eg. 0.5.to_fraction => [1,2]

   1  
   2  class Float
   3    def number_decimal_places
   4      self.to_s.length-2
   5    end
   6    
   7    def to_fraction
   8      higher = 10**self.number_decimal_places
   9      lower = self*higher
  10  
  11      gcden = greatest_common_divisor(higher, lower)
  12  
  13      return (lower/gcden).round, (higher/gcden).round
  14    end
  15    
  16  private
  17  
  18    def greatest_common_divisor(a, b)
  19       while a%b != 0
  20         a,b = b.round,(a%b).round
  21       end 
  22       return b
  23    end
  24  end
  25  
« Newer Snippets
Older Snippets »
Showing 1-1 of 1 total  RSS