Sha256: 5237511c3f302a6bbd6b2af9e2cc5309feb6f51aa638e492ab38079ffc46da1a

Contents?: true

Size: 604 Bytes

Versions: 2

Compression:

Stored size: 604 Bytes

Contents

class Numeric
  # A more precise rounding. ~4 times slower than simple round
  #
  #     3.904605.round(2)
  #     # => 3.9
  #     3.904605.precision(2) 
  #     # => 3.91
  #
  #     37.9945.round(2)    
  #     # => 37.99                        
  #     37.9945.precision(2)
  #     # => 38.0                         
  def precision(precision = 0)
    power = 10 ** precision

    if precision == 0
      self.round
    else
      powered = self * power

      (precision - 1).downto(0).each do |i|
        powered = powered.round(i).to_f
      end

      powered.to_f / power.to_f
    end
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
inactive_support-1.0.0 lib/inactive_support/numeric/precision.rb
inactive_support-0.1.0 lib/inactive_support/numeric/precision.rb