Module: Artworker::Fractions

Defined in:
lib/artworker/fractions.rb

Class Method Summary collapse

Class Method Details

.round_to_nearest_fraction(value = 0, to_nearest_fraction) ⇒ Object



51
52
53
54
55
56
57
58
59
60
61
62
# File 'lib/artworker/fractions.rb', line 51

def self.round_to_nearest_fraction(value=0, 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 = 0) ⇒ Object



13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
# File 'lib/artworker/fractions.rb', line 13

def self.to_f(value=0)
  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 = 0, args = {}) ⇒ Object



32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
# File 'lib/artworker/fractions.rb', line 32

def self.to_s(value=0, args={})
  whole_number = value.to_f.truncate.to_i

  if whole_number == 0
    fractional_part_to_string(value, args[:to_nearest])
  else
    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