Skip to content
This repository
Browse code

Allow Float#round to take a precision argument. Closes #8626 [norbert]

git-svn-id: http://svn-commit.rubyonrails.org/rails/trunk@7401 5ecf4fe2-1ee6-0310-87b1-e25e094e27de
  • Loading branch information...
commit f0dbd22c4647bf8e37fd9b58ce6652aaca27376e 1 parent 2183782
Michael Koziarski NZKoz authored
5 activesupport/lib/active_support/core_ext/float.rb
... ... @@ -0,0 +1,5 @@
  1 +require File.dirname(__FILE__) + '/float/rounding'
  2 +
  3 +class Float #:nodoc:
  4 + include ActiveSupport::CoreExtensions::Float::Rounding
  5 +end
22 activesupport/lib/active_support/core_ext/float/rounding.rb
... ... @@ -0,0 +1,22 @@
  1 +module 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
  22 +end
25 activesupport/test/core_ext/float_ext_test.rb
... ... @@ -0,0 +1,25 @@
  1 +require File.dirname(__FILE__) + '/../abstract_unit'
  2 +
  3 +class 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
  25 +end

0 comments on commit f0dbd22

Please sign in to comment.
Something went wrong with that request. Please try again.