Sha256: 25e3fbcac1347efa6db07eb5f9b1cdd6278e9044a9cd8ed87f0e2e2f06a2ca02

Contents?: true

Size: 1.53 KB

Versions: 21

Compression:

Stored size: 1.53 KB

Contents

require 'facets/core/float/round_off'

class Float

  # Rounds to the nearest _n_th degree.
  #
  #   4.555.round_to(1)     #=> 5.0
  #   4.555.round_to(0.1)   #=> 4.6
  #   4.555.round_to(0.01)  #=> 4.56
  #   4.555.round_to(0)     #=> 4.555
  #
  def round_to( n ) #n=1
    return self if n == 0
    (self * (1.0 / n)).round_off.to_f / (1.0 / n)
  end
end

class Numeric
  # To properly support Float's rounding methods,
  # Numeric must also be augmented.
  def round_to(*args)
    self.to_f.round_to(*args)
  end
end

class Integer
  # To properly support Float's rounding methods,
  # Integer must also be augmented.
  def round_to(*args)
    self.to_f.round_to(*args)
  end
end


#  _____         _
# |_   _|__  ___| |_
#   | |/ _ \/ __| __|
#   | |  __/\__ \ |_
#   |_|\___||___/\__|
#
=begin test

  require 'test/unit'

  class TCFloat < Test::Unit::TestCase

    def setup
      @f0 = [ 0, 10, 15, 105 ]
      @f1 = [ 10.1, 10.01, 10.9, 10.09, 10.5, 10.05, 10.49 ]
    end

    def test_round_to_arg1
      fr = @f0.collect { |f| f.round_to(0.1) }
      assert_equal( [0,10,15,105], fr )
      fr = @f1.collect { |f| f.round_to(0.1) }
      assert_equal( [10.1,10.0,10.9,10.1,10.5,10.1,10.5], fr )
    end

    def test_round_to_arg10
      fr = @f0.collect { |f| f.round_to(10) }
      assert_equal( [0,10,20,110], fr )
      fr = @f1.collect { |f| f.round_to(10) }
      assert_equal( [10,10,10,10,10,10,10], fr )
    end

    def test_round_off
      assert_equal( 1.0, 1.2.round_off )
      assert_equal( 2.0, 1.8.round_off )
    end

  end

=end

Version data entries

21 entries across 21 versions & 1 rubygems

Version Path
facets-1.2.1 lib/facets/core/float/round_to.rb
facets-1.3.0 lib/facets/core/float/round_to.rb
facets-1.3.1 lib/facets/core/float/round_to.rb
facets-1.3.3 lib/facets/core/float/round_to.rb
facets-1.3.2 lib/facets/core/float/round_to.rb
facets-1.4.2 lib/facets/core/float/round_to.rb
facets-1.4.0 lib/facets/core/float/round_to.rb
facets-1.4.1 lib/facets/core/float/round_to.rb
facets-1.4.3 lib/facets/core/float/round_to.rb
facets-1.4.5 lib/facets/core/float/round_to.rb
facets-1.4.4 lib/facets/core/float/round_to.rb
facets-1.7.38 lib/facets/core/float/round_to.rb
facets-1.7.30 lib/facets/core/float/round_to.rb
facets-1.7.0 lib/facets/core/float/round_to.rb
facets-1.7.46 lib/facets/core/float/round_to.rb
facets-1.8.49 lib/facets/core/float/round_to.rb
facets-1.8.0 lib/facets/core/float/round_to.rb
facets-1.8.20 lib/facets/core/float/round_to.rb
facets-1.8.51 lib/facets/core/float/round_to.rb
facets-1.8.54 lib/facets/core/float/round_to.rb