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

Ticket #8626: round_with_precision.diff

File round_with_precision.diff, 1.4 kB (added by norbert, 2 years ago)
  • activesupport/test/core_ext/float_test.rb

    old new  
     1require File.dirname(__FILE__) + '/../abstract_unit' 
     2 
     3class FloatTests < Test::Unit::TestCase 
     4  def test_round 
     5    @float = 1.337 
     6    assert_equal 1,    @float.round 
     7    assert_equal 1,    @float.round(0) 
     8    assert_equal 1,    @float.round(nil) 
     9    assert_equal 1.3,  @float.round(1) 
     10    assert_equal 1.3,  @float.round('1') 
     11    assert_equal 1.3,  @float.round(1.0) 
     12    assert_equal 1.34, @float.round(2) 
     13  end 
     14end 
  • activesupport/lib/active_support/core_ext/float.rb

    old new  
     1class Float 
     2  alias_method :round_without_precision, :round 
     3 
     4  # Rounds the float, optionally with a specified precision. 
     5  # 
     6  #   x = 1.337 
     7  #   x.round    # => 1 
     8  #   x.round(1) # => 1.3 
     9  #   x.round(2) # => 1.34 
     10  def round(precision = nil) 
     11    precision = precision.to_i 
     12    if precision == 0 
     13      round_without_precision 
     14    else 
     15      (self * (10 ** precision)).round / (10 ** precision).to_f 
     16    end  
     17  end 
     18end