bcardarella (owner)

Forks

Revisions

gist: 185644 Download_button fork
public
Description:
Float#round_to_faction
Public Clone URL: git://gist.github.com/185644.git
Embed All Files: show embed
round_to_precision.rb #
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
class Float
 
  # Takes a fraction and will round a float to the nearest multiple
  # >> k = 0.4
  # >> k.round_to_fraction
  # => 0.5
  # >> k = 0.75
  # >> k.round_to_fraction
  # => 1.0
  # >> k.round_to_fraction(0.65)
  # => 0.65
  def round_to_fraction(fraction = 0.5)
    if fraction >= 1.0
      raise "fraction must be below 1.0"
    elsif fraction > 0.5
      num = 2
    else
      num = (1 / fraction).to_i
    end
    
    modifier = 0.0
    
    (1..num).each do |n|
      mod_difference = ((modifier + self.to_i) - self).abs
      if num == n
        difference = ((1.0 + self.to_i) - self).abs
      else
        difference = (((n * fraction) + self.to_i) - self).abs
      end
      
      if difference <= mod_difference
        if num == n
          modifier = 1.0
        else
          modifier = fraction * n
        end
      end
    end
      
    self.to_i + modifier
  end
end