# Behavior for rendering and rounding fractions with respect to a denominator. # Two methods are added to the Numeric class. # # with_fraction is an alternative to to_s that renders a value as a string # with a whole number and any decimal part as a fraction. # # round_to_nearest rounds a value such that a fractional part with the given # denominator will have integer as its numerator. # Behavior added to Numeric by eymiha_math class Numeric # Renders a numeric value as a whole number and a fraction with a given # denominator, separated with a given separator, and optionally showing # fractions with a numerator of zero. def with_fraction(denominator=1,separator='-',show_zero=false) sign = self <=> 0 unsigned = self*sign whole = (((unsigned*denominator).round)/denominator).floor numerator = ((unsigned-whole)*denominator).round "#{sign*whole}#{(numerator != 0)||show_zero ? "#{separator}#{numerator}/#{denominator}" : ""}" end # Returns a numeric value such that any remainder is evenly divided by # the given denominator. def round_to_nearest(denominator=1) ((self*denominator).round)/(1.0*denominator) end end