将小数转成分数

实现一

  class Float
    def decimal_places
      self.to_s.length - 2
    end

    def to_fraction
      higher = 10 ** self.decimal_places
      lower = self * higher
      gcden = divisor(higher, lower)
      return (lower / gcden).round.to_s + "/" + (higher / gcden).round.to_s
    end

    private
    def divisor(a, b)
      while a % b != 0
        a, b = b.round,(a % b).round
      end
      return b
    end
  end 

 

具体示例:

 

  puts  0.5.to_fraction  # => 1/2
  puts  0.25.to_fraction # => 1/4

 

实现二

class Float
  def fraction
    fraction = case self.abs % 1.0
    when 1.0 / 2 then '½'  
    when 1.0 / 4 then '¼'  
    when 3.0 / 4 then '¾'  
    when 1.0 / 3 then '⅓'  
    when 2.0 / 3 then '⅔' 
    when 1.0 / 5 then '⅕' 
    when 2.0 / 5 then '⅖'  
    when 3.0 / 5 then '⅗' 
    when 4.0 / 5 then '⅘'  
    when 1.0 / 6 then '⅙' 
    when 5.0 / 6 then '⅚' 
    when 1.0 / 8 then '⅛' 
    when 3.0 / 8 then '⅜'  
    when 5.0 / 8 then '⅝' 
    when 7.0 / 8 then '⅞'  
    end
    if fraction
      body = case self.floor
      when -1 then '-'
      when  0 then ''
      else self.to_i.to_s
      end
      body + fraction
    else
      self.to_s
    end
  end
end

 

具体示例:

 

    puts (0.1).fraction   # => 0.1
    puts (0.25).fraction  # => ¼
    puts (0.50).fraction  # => ½
    puts (0.75).fraction  # => ¾
    puts (1.0).fraction   # => 1.0
    puts (2.25).fraction  # => 2¼
    puts (3.5).fraction   # => 3½
    puts (4.75).fraction  # => 4¾
    puts (5.85).fraction  # => 5.85
    puts (-1.5).fraction  # => -1½
    puts (-1.6).fraction  # => -1.6;
    puts (-0.25).fraction # => -¼

 

你可能感兴趣的:(将小数转成分数)