Sha256: 7405c538fd71a6d9bb702f4e92a4fabac02686943b61655aa80e3615481adba1

Contents?: true

Size: 521 Bytes

Versions: 1

Compression:

Stored size: 521 Bytes

Contents

# 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
class Numeric
  def precision(precision = 0)
    power = 10**precision

    if precision == 0
      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

1 entries across 1 versions & 1 rubygems

Version Path
inactive_support-1.1.0 lib/inactive_support/numeric/precision.rb