Ticket #6351: to_currency_helper_with_order.2.patch
| File to_currency_helper_with_order.2.patch, 3.0 kB (added by chrismear, 2 years ago) |
|---|
-
actionpack/test/template/number_helper_test.rb
old new 25 25 assert_equal("$1,234,567,890", number_to_currency(1234567890.50, {:precision => 0})) 26 26 assert_equal("$1,234,567,890.5", number_to_currency(1234567890.50, {:precision => 1})) 27 27 assert_equal("£1234567890,50", number_to_currency(1234567890.50, {:unit => "£", :separator => ",", :delimiter => ""})) 28 assert_equal("1,234,567,890.50 GBP", number_to_currency(1234567890.50, {:unit => "GBP", :order => [:number, :unit]})) 28 29 assert_equal("$1,234,567,890.50", number_to_currency("1234567890.50")) 29 30 assert_equal("$x.", number_to_currency("x")) 30 31 assert_nil number_to_currency(nil) -
actionpack/lib/action_view/helpers/number_helper.rb
old new 46 46 # * <tt>:unit</tt> - Sets the denomination of the currency, defaults to "$" 47 47 # * <tt>:separator</tt> - Sets the separator between the units, defaults to "." 48 48 # * <tt>:delimiter</tt> - Sets the thousands delimiter, defaults to "," 49 # * <tt>:order</tt> - Sets the order that the unit and the number appear, defaults to [:unit, :number]. If the unit comes after the number, a space will automatically be inserted before the unit. 49 50 # 50 51 # number_to_currency(1234567890.50) => $1,234,567,890.50 51 52 # number_to_currency(1234567890.506) => $1,234,567,890.51 52 53 # number_to_currency(1234567890.506, :precision => 3) => $1,234,567,890.506 53 54 # number_to_currency(1234567890.50, :unit => "£", :separator => ",", :delimiter => "") 54 55 # => £1234567890,50 56 # number_to_currency(1234567890.50, :unit => "GBP", :order => [:number, :unit]) => 1,234,567,890.50 GBP 55 57 def number_to_currency(number, options = {}) 56 58 options = options.stringify_keys 57 59 precision = options["precision"] || 2 58 60 unit = options["unit"] || "$" 59 61 separator = precision > 0 ? options["separator"] || "." : "" 60 62 delimiter = options["delimiter"] || "," 63 order = options["order"] || [:unit, :number] 61 64 65 unit = " " + unit 66 62 67 begin 63 parts = number_with_precision(number, precision).split('.') 64 unit + number_with_delimiter(parts[0], delimiter) + separator + parts[1].to_s 68 output = order.map do |item| 69 case item 70 when :unit 71 unit 72 when :number 73 parts = number_with_precision(number, precision).split('.') 74 number_with_delimiter(parts[0], delimiter) + separator + parts[1].to_s 75 end 76 end 77 output.join("").strip 65 78 rescue 66 79 number 67 80 end