Ruby on Rails | Screencasts | Download | Documentation | Weblog | Community | Source

Ticket #8626: round_with_precision.3.diff

File round_with_precision.3.diff, 2.4 kB (added by norbert, 1 year ago)
  • activesupport/test/core_ext/float_ext_test.rb

    old new  
     1require File.dirname(__FILE__) + '/../abstract_unit' 
     2 
     3class FloatExtRoundingTests < Test::Unit::TestCase 
     4  def test_round_for_positive_number 
     5    assert_equal 1,    1.4.round 
     6    assert_equal 2,    1.6.round 
     7    assert_equal 2,    1.6.round(0) 
     8    assert_equal 1.4,  1.4.round(1) 
     9    assert_equal 1.4,  1.4.round(3) 
     10    assert_equal 1.5,  1.45.round(1) 
     11    assert_equal 1.45, 1.445.round(2) 
     12  end 
     13 
     14  def test_round_for_negative_number 
     15    assert_equal( -1,   -1.4.round ) 
     16    assert_equal( -2,   -1.6.round ) 
     17    assert_equal( -1.4, -1.4.round(1) ) 
     18    assert_equal( -1.5, -1.45.round(1) ) 
     19  end 
     20 
     21  def test_round_with_negative_precision 
     22    assert_equal 123460.0, 123456.0.round(-1) 
     23    assert_equal 123500.0, 123456.0.round(-2) 
     24  end 
     25end 
  • activesupport/lib/active_support/core_ext/float/rounding.rb

    old new  
     1module ActiveSupport #:nodoc: 
     2  module CoreExtensions #:nodoc: 
     3    module Float #:nodoc: 
     4      module Rounding 
     5        def self.included(base) #:nodoc: 
     6          base.send(:alias_method, :round_without_precision, :round) 
     7          base.send(:alias_method, :round, :round_with_precision) 
     8        end 
     9 
     10        # Rounds the float with the specified precision. 
     11        # 
     12        #   x = 1.337 
     13        #   x.round    # => 1 
     14        #   x.round(1) # => 1.3 
     15        #   x.round(2) # => 1.34 
     16        def round_with_precision(precision = nil) 
     17          precision.nil? ? round_without_precision : (self * (10 ** precision)).round / (10 ** precision).to_f 
     18        end 
     19      end 
     20    end 
     21  end 
     22end 
  • activesupport/lib/active_support/core_ext/float.rb

    old new  
     1require File.dirname(__FILE__) + '/float/rounding' 
     2 
     3class Float #:nodoc: 
     4  include ActiveSupport::CoreExtensions::Float::Rounding 
     5end