From 8c81491f85693fe6327453f92c0dd4d323fe3869 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Wojciech=20Wn=C4=99trzak?= Date: Thu, 10 Mar 2011 12:59:51 +0100 Subject: [PATCH] added rounding extension for integer to be consistent with ruby 1.9 --- .../lib/active_support/core_ext/integer.rb | 1 + .../active_support/core_ext/integer/rounding.rb | 20 +++++++++++++++++++ activesupport/test/core_ext/integer_ext_test.rb | 21 ++++++++++++++++++++ 3 files changed, 42 insertions(+), 0 deletions(-) create mode 100644 activesupport/lib/active_support/core_ext/integer/rounding.rb diff --git a/activesupport/lib/active_support/core_ext/integer.rb b/activesupport/lib/active_support/core_ext/integer.rb index a44a1b4..a7593d5 100644 --- a/activesupport/lib/active_support/core_ext/integer.rb +++ b/activesupport/lib/active_support/core_ext/integer.rb @@ -1,3 +1,4 @@ require 'active_support/core_ext/integer/multiple' require 'active_support/core_ext/integer/inflections' require 'active_support/core_ext/integer/time' +require 'active_support/core_ext/integer/rounding' diff --git a/activesupport/lib/active_support/core_ext/integer/rounding.rb b/activesupport/lib/active_support/core_ext/integer/rounding.rb new file mode 100644 index 0000000..998eeba --- /dev/null +++ b/activesupport/lib/active_support/core_ext/integer/rounding.rb @@ -0,0 +1,20 @@ +class Integer + alias precisionless_round round + private :precisionless_round + + # Rounds the integer with the specified precision. + # + # x = 1233 + # x.round # => 1233 + # x.round(1) # => 1233 + # x.round(-1) # => 1230 + # x.round(-5) # => 0 + def round(precision = nil) + if precision + magnitude = 10 ** precision + ((self * magnitude).round / magnitude).to_i + else + precisionless_round + end + end +end if RUBY_VERSION < '1.9' diff --git a/activesupport/test/core_ext/integer_ext_test.rb b/activesupport/test/core_ext/integer_ext_test.rb index fe8c7eb..161383b 100644 --- a/activesupport/test/core_ext/integer_ext_test.rb +++ b/activesupport/test/core_ext/integer_ext_test.rb @@ -24,4 +24,25 @@ class IntegerExtTest < Test::Unit::TestCase assert_equal '8th', 8.ordinalize 1000000000000000000000000000000000000000000000000000000000000000000000.ordinalize end + + def test_round_for_positive_number + assert_equal 1, 1.round + assert_equal 2, 2.round(1) + end + + def test_round_for_negative_number + assert_equal( -1, -1.round ) + assert_equal( -5, -5.round(1) ) + end + + def test_round_with_negative_precision + assert_equal 123460, 123456.round(-1) + assert_equal 123500, 123456.round(-2) + assert_equal -123500, -123456.round(-2) + end + + def test_not_changing_class_after_round + assert_equal Fixnum, 123456.round(1).class + assert_equal Fixnum, 123456.round(-1).class + end end -- 1.7.1.1