Ticket #11149: format_option_for_number_to_currency.diff
| File format_option_for_number_to_currency.diff, 2.7 kB (added by lylo, 5 months ago) |
|---|
-
actionpack/test/template/number_helper_test.rb
old new 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 27 assert_equal("$1,234,567,890.50", number_to_currency("1234567890.50")) 28 assert_equal("1,234,567,890.50 Kč", number_to_currency("1234567890.50", {:unit => "Kč", :format => "%n %u"})) 28 29 assert_equal("$x.", number_to_currency("x")) 29 30 assert_nil number_to_currency(nil) 30 31 end -
actionpack/lib/action_view/helpers/number_helper.rb
old new 54 54 # * <tt>:unit</tt> - Sets the denomination of the currency (defaults to "$"). 55 55 # * <tt>:separator</tt> - Sets the separator between the units (defaults to "."). 56 56 # * <tt>:delimiter</tt> - Sets the thousands delimiter (defaults to ","). 57 # * <tt>:format</tt> - Sets the format of the output string (defaults to "%u%n"). The field types are: 57 58 # 59 # %u The currency unit 60 # %n The number 61 # 58 62 # ==== Examples 59 63 # number_to_currency(1234567890.50) # => $1,234,567,890.50 60 64 # number_to_currency(1234567890.506) # => $1,234,567,890.51 … … 62 66 # 63 67 # number_to_currency(1234567890.50, :unit => "£", :separator => ",", :delimiter => "") 64 68 # # => £1234567890,50 69 # number_to_currency(1234567890.50, :unit => "£", :separator => ",", :delimiter => "", :format => "%n %u") 70 # # => 1234567890,50 £ 65 71 def number_to_currency(number, options = {}) 66 72 options = options.stringify_keys 67 73 precision = options["precision"] || 2 68 74 unit = options["unit"] || "$" 69 75 separator = precision > 0 ? options["separator"] || "." : "" 70 76 delimiter = options["delimiter"] || "," 77 format = options["format"] || "%u%n" 71 78 72 79 begin 73 80 parts = number_with_precision(number, precision).split('.') 74 unit + number_with_delimiter(parts[0], delimiter) + separator + parts[1].to_s81 format.gsub(/%n/, number_with_delimiter(parts[0], delimiter) + separator + parts[1].to_s).gsub(/%u/, unit) 75 82 rescue 76 83 number 77 84 end