Skip to content

Commit

Permalink
Added format to percentage
Browse files Browse the repository at this point in the history
  • Loading branch information
Rodrigo Flores authored and prasath committed Feb 7, 2012
1 parent aa871d9 commit eeac7a7
Show file tree
Hide file tree
Showing 3 changed files with 11 additions and 2 deletions.
11 changes: 9 additions & 2 deletions actionpack/lib/action_view/helpers/number_helper.rb
Expand Up @@ -169,6 +169,8 @@ def number_to_currency(number, options = {})
# * <tt>:delimiter</tt> - Sets the thousands delimiter (defaults to "").
# * <tt>:strip_insignificant_zeros</tt> - If +true+ removes insignificant zeros after the decimal separator
# (defaults to +false+).
# * <tt>:format</tt> - Specifies the format of the percentage string
# The number field is <tt>%n</tt> (defaults to "%n%").
# * <tt>:raise</tt> - If true, raises +InvalidNumberError+ when the argument is invalid.
#
# ==== Examples
Expand All @@ -180,6 +182,7 @@ def number_to_currency(number, options = {})
# number_to_percentage(302.24398923423, :precision => 5) # => 302.24399%
# number_to_percentage(1000, :locale => :fr) # => 1 000,000%
# number_to_percentage("98a") # => 98a%
# number_to_percentage(100, :format => "%n %") # => 100 %
#
# number_to_percentage("98a", :raise => true) # => InvalidNumberError
def number_to_percentage(number, options = {})
Expand All @@ -193,13 +196,17 @@ def number_to_percentage(number, options = {})

options = options.reverse_merge(defaults)

format = options[:format] || "%n%"

begin
"#{number_with_precision(number, options.merge(:raise => true))}%".html_safe
value = number_with_precision(number, options.merge(:raise => true))
format.gsub(/%n/, value).html_safe
rescue InvalidNumberError => e
if options[:raise]
raise
else
e.number.to_s.html_safe? ? "#{e.number}%".html_safe : "#{e.number}%"
formatted_number = e.number.to_s.html_safe? ? format.gsub(/%n/, e.number).html_safe : format.gsub(/%n/, e.number)
formatted_number.html_safe? ? formatted_number.html_safe : formatted_number
end
end
end
Expand Down
1 change: 1 addition & 0 deletions actionpack/lib/action_view/locale/en.yml
Expand Up @@ -37,6 +37,7 @@
# precision:
# significant: false
# strip_insignificant_zeros: false
format: "%n%"

# Used in number_to_precision()
precision:
Expand Down
1 change: 1 addition & 0 deletions actionpack/test/template/number_helper_test.rb
Expand Up @@ -57,6 +57,7 @@ def test_number_to_percentage
assert_equal("1000.000%", number_to_percentage("1000"))
assert_equal("123.4%", number_to_percentage(123.400, :precision => 3, :strip_insignificant_zeros => true))
assert_equal("1.000,000%", number_to_percentage(1000, :delimiter => '.', :separator => ','))
assert_equal("1000.000 %", number_to_percentage(1000, :format => "%n %"))
end

def test_number_with_delimiter
Expand Down

0 comments on commit eeac7a7

Please sign in to comment.