
require 'facets/core/float/round_off'

class Float

  # Rounds to the given decimal position.
  #
  #   4.555.round_at(0)  #=> 5.0
  #   4.555.round_at(1)  #=> 4.6
  #   4.555.round_at(2)  #=> 4.56
  #   4.555.round_at(3)  #=> 4.555
  #
  def round_at( d ) #d=0
    (self * (10.0 ** d)).round_off.to_f / (10.0 ** d)
  end
end

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

class Integer
  # To properly support Float's rounding methods,
  # Integer must also be augmented.
  def round_at(*args)
    self.to_f.round_at(*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_at_arg1
      fr = @f0.collect{ |f| f.round_at(1) }
      assert_equal( [0,10,15,105], fr )
      fr = @f1.collect { |f| f.round_at(1) }
      assert_equal( [10.1,10.0,10.9,10.1,10.5,10.1,10.5], fr )
    end

    def test_round_at_arg2
      fr = @f0.collect { |f| f.round_at(2) }
      assert_equal( [0,10,15,105], fr )
      fr = @f1.collect { |f| f.round_at(2) }
      assert_equal( [10.1,10.01,10.9,10.09,10.5,10.05,10.49], 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
