From 0e62c773f603f885743d52f44fb032290f809cae Mon Sep 17 00:00:00 2001 From: David Heinemeier Hansson Date: Mon, 24 Mar 2008 21:12:55 +0000 Subject: Fixed NumberHelper#number_with_precision to properly round in a way that works equally on Mac, Windows, Linux (closes #11409, #8275, #10090, #8027) [zhangyuanyi] git-svn-id: http://svn-commit.rubyonrails.org/rails/trunk@9086 5ecf4fe2-1ee6-0310-87b1-e25e094e27de --- actionpack/CHANGELOG | 4 +++- actionpack/lib/action_view/helpers/number_helper.rb | 4 ++-- actionpack/test/template/number_helper_test.rb | 2 ++ 3 files changed, 7 insertions(+), 3 deletions(-) (limited to 'actionpack') diff --git a/actionpack/CHANGELOG b/actionpack/CHANGELOG index a1e487c2e1..fd4d8e59d8 100644 --- a/actionpack/CHANGELOG +++ b/actionpack/CHANGELOG @@ -1,6 +1,8 @@ *SVN* -# Allow the #simple_format text_helper to take an html_options hash for each paragraph. #2448 [Francois Beausoleil, thechrisoshow] +* Fixed NumberHelper#number_with_precision to properly round in a way that works equally on Mac, Windows, Linux (closes #11409, #8275, #10090, #8027) [zhangyuanyi] + +* Allow the #simple_format text_helper to take an html_options hash for each paragraph. #2448 [Francois Beausoleil, thechrisoshow] * Fix regression from filter refactoring where re-adding a skipped filter resulted in it being called twice. [rick] diff --git a/actionpack/lib/action_view/helpers/number_helper.rb b/actionpack/lib/action_view/helpers/number_helper.rb index fe40725402..120bb4cc1f 100644 --- a/actionpack/lib/action_view/helpers/number_helper.rb +++ b/actionpack/lib/action_view/helpers/number_helper.rb @@ -144,11 +144,11 @@ module ActionView # # ==== Examples # number_with_precision(111.2345) # => 111.235 - # number_with_precision(111.2345, 2) # => 111.24 + # number_with_precision(111.2345, 2) # => 111.23 # number_with_precision(13, 5) # => 13.00000 # number_with_precision(389.32314, 0) # => 389 def number_with_precision(number, precision=3) - "%01.#{precision}f" % number + "%01.#{precision}f" % ((Float(number) * (10 ** precision)).round.to_f / 10 ** precision) rescue number end diff --git a/actionpack/test/template/number_helper_test.rb b/actionpack/test/template/number_helper_test.rb index 00e5bd6461..7065ca7a84 100644 --- a/actionpack/test/template/number_helper_test.rb +++ b/actionpack/test/template/number_helper_test.rb @@ -56,9 +56,11 @@ class NumberHelperTest < Test::Unit::TestCase def test_number_with_precision assert_equal("111.235", number_with_precision(111.2346)) + assert_equal("31.83", number_with_precision(31.825, 2)) assert_equal("111.23", number_with_precision(111.2346, 2)) assert_equal("111.00", number_with_precision(111, 2)) assert_equal("111.235", number_with_precision("111.2346")) + assert_equal("31.83", number_with_precision("31.825", 2)) assert_equal("112", number_with_precision(111.50, 0)) assert_equal("1234567892", number_with_precision(1234567891.50, 0)) -- cgit v1.2.3