Module: Fractional
- Defined in:
- lib/fractional.rb
Class Method Summary collapse
- .round_to_nearest_fraction(value, to_nearest_fraction) ⇒ Object
- .to_f(value) ⇒ Object
- .to_s(value, args = {}) ⇒ Object
Class Method Details
.round_to_nearest_fraction(value, to_nearest_fraction) ⇒ Object
43 44 45 46 47 48 49 50 51 52 53 54 |
# File 'lib/fractional.rb', line 43 def self.round_to_nearest_fraction(value, to_nearest_fraction) if value.is_a? String to_nearest_float = to_f(to_nearest_fraction) to_s((self.to_f(value) / to_nearest_float).round * to_nearest_float) else to_nearest_float = to_f(to_nearest_fraction) (value / to_nearest_float).round * to_nearest_float end end |
.to_f(value) ⇒ Object
5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
# File 'lib/fractional.rb', line 5 def self.to_f(value) result = 0 if mixed_fraction?(value) whole, numerator, denominator = value.scan(/(\-?\d*)\s(\d+)\/(\d+)/).flatten result = (numerator.to_f / denominator.to_f) + whole.to_f.abs result = whole.to_f > 0 ? result : -result elsif single_fraction?(value) numerator, denominator = value.split("/") result = numerator.to_f / denominator.to_f else result = value.to_f end result end |
.to_s(value, args = {}) ⇒ Object
24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 |
# File 'lib/fractional.rb', line 24 def self.to_s(value, args={}) whole_number = value.to_f.truncate.to_i if whole_number == 0 # Single fraction fractional_part_to_string(value, args[:to_nearest]) else # Mixed fraction decimal_point_value = get_decimal_point_value(value.to_f) return whole_number.to_s if decimal_point_value == 0 fractional_part = fractional_part_to_string(decimal_point_value.abs, args[:to_nearest]) if (fractional_part == "1") || (fractional_part == "0") (whole_number + fractional_part.to_i).to_s else whole_number.to_s + " " + fractional_part end end end |