class NumberMuncher::ToFraction

Attributes

factor[R]
rational[R]
separator[R]
unicode[R]
unicode?[R]

Public Class Methods

new(unicode: true, separator: nil, factor: 0.001) click to toggle source
# File lib/number_muncher/to_fraction.rb, line 3
def initialize(unicode: true, separator: nil, factor: 0.001)
  @unicode = unicode
  @separator = separator
  @factor = factor
end

Public Instance Methods

call(number, round_to: nil) click to toggle source
# File lib/number_muncher/to_fraction.rb, line 9
def call(number, round_to: nil)
  return '' unless number

  @rational = rationalize(number, round_to)
  return '0' if rational.zero?

  separator = glyph ? '' : ' '
  parts = [whole, glyph || fraction].compact
  "#{sign}#{parts.map(&:to_s).join(separator)}"
end

Private Instance Methods

fraction() click to toggle source
# File lib/number_muncher/to_fraction.rb, line 41
def fraction
  value = (whole ? rational.abs - whole : rational).abs
  value.zero? ? nil : value
end
glyph() click to toggle source
# File lib/number_muncher/to_fraction.rb, line 29
def glyph
  return nil unless unicode? && fraction

  Unicode::MAPPING.key(fraction)
end
rationalize(number, round_to) click to toggle source
# File lib/number_muncher/to_fraction.rb, line 25
def rationalize(number, round_to)
  Numeric.new(number).round(round_to).rationalize(factor)
end
sign() click to toggle source
# File lib/number_muncher/to_fraction.rb, line 46
def sign
  '-' if rational.negative?
end
whole() click to toggle source
# File lib/number_muncher/to_fraction.rb, line 35
def whole
  return if (-1.0.next_float...1).cover?(rational)

  (rational.numerator / rational.denominator).abs
end