Ticket #6351: to_currency_helper_with_order.3.patch
| File to_currency_helper_with_order.3.patch, 3.2 kB (added by jesperronn, 1 year ago) |
|---|
-
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 50 # [:unit, :number]. If the unit comes after the number, a space will automatically be 51 # inserted before the unit. 49 52 # 50 53 # number_to_currency(1234567890.50) => $1,234,567,890.50 51 54 # number_to_currency(1234567890.506) => $1,234,567,890.51 52 55 # number_to_currency(1234567890.506, :precision => 3) => $1,234,567,890.506 53 56 # number_to_currency(1234567890.50, :unit => "£", :separator => ",", :delimiter => "") 54 57 # => £1234567890,50 58 # number_to_currency(1234567890.50, :unit => "GBP", :order => [:number, :unit]) => 1,234,567,890.50 GBP 55 59 def number_to_currency(number, options = {}) 56 60 options = options.stringify_keys 57 61 precision = options["precision"] || 2 58 62 unit = options["unit"] || "$" 59 63 separator = precision > 0 ? options["separator"] || "." : "" 60 64 delimiter = options["delimiter"] || "," 61 65 order = options["order"] || [:unit, :number] 66 67 unit = " " + unit 62 68 begin 63 parts = number_with_precision(number, precision).split('.') 64 unit + number_with_delimiter(parts[0], delimiter) + separator + parts[1].to_s 69 output = order.map do |item| 70 case item 71 when :unit 72 unit 73 when :number 74 parts = number_with_precision(number, precision).split('.') 75 number_with_delimiter(parts[0], delimiter) + separator + parts[1].to_s 76 end 77 end 78 output = output.join("").strip 65 79 rescue 66 number80 output = number 67 81 end 82 output 68 83 end 69 84 70 85 # Formats a +number+ as a percentage string. You can customize the -
actionpack/test/template/number_helper_test.rb
old new 24 24 assert_equal("$1,234,567,892", number_to_currency(1234567891.50, {:precision => 0})) 25 25 assert_equal("$1,234,567,890.5", number_to_currency(1234567890.50, {:precision => 1})) 26 26 assert_equal("£1234567890,50", number_to_currency(1234567890.50, {:unit => "£", :separator => ",", :delimiter => ""})) 27 assert_equal("1,234,567,890.50 GBP", number_to_currency(1234567890.50, {:unit => "GBP", :order => [:number, :unit]})) 27 28 assert_equal("$1,234,567,890.50", number_to_currency("1234567890.50")) 28 29 assert_equal("$x.", number_to_currency("x")) 29 30 assert_nil number_to_currency(nil)