number_helper.rb 14.8 KB
Newer Older
1
require 'active_support/core_ext/big_decimal/conversions'
J
Jeremy Kemper 已提交
2 3
require 'active_support/core_ext/float/rounding'

4
module ActionView
5
  module Helpers #:nodoc:
6
    # Provides methods for converting numbers into formatted strings.
7 8
    # Methods are provided for phone numbers, currency, percentage,
    # precision, positional notation, and file size.
9
    module NumberHelper
10
      # Formats a +number+ into a US phone number (e.g., (555) 123-9876). You can customize the format
11
      # in the +options+ hash.
12 13
      #
      # ==== Options
14
      # * <tt>:area_code</tt>  - Adds parentheses around the area code.
15
      # * <tt>:delimiter</tt>  - Specifies the delimiter to use (defaults to "-").
16
      # * <tt>:extension</tt>  - Specifies an extension to add to the end of the
17
      #   generated number.
18 19
      # * <tt>:country_code</tt>  - Sets the country code for the phone number.
      #
20
      # ==== Examples
21
      #  number_to_phone(5551234)                                           # => 555-1234
22 23 24 25 26 27
      #  number_to_phone(1235551234)                                        # => 123-555-1234
      #  number_to_phone(1235551234, :area_code => true)                    # => (123) 555-1234
      #  number_to_phone(1235551234, :delimiter => " ")                     # => 123 555 1234
      #  number_to_phone(1235551234, :area_code => true, :extension => 555) # => (123) 555-1234 x 555
      #  number_to_phone(1235551234, :country_code => 1)                    # => +1-123-555-1234
      #
28
      #  number_to_phone(1235551234, :country_code => 1, :extension => 1343, :delimiter => ".")
29
      #  => +1.123.555.1234 x 1343
30
      def number_to_phone(number, options = {})
31
        number       = number.to_s.strip unless number.nil?
32 33 34 35 36
        options      = options.symbolize_keys
        area_code    = options[:area_code] || nil
        delimiter    = options[:delimiter] || "-"
        extension    = options[:extension].to_s.strip || nil
        country_code = options[:country_code] || nil
37

38
        begin
39 40 41 42 43
          str = ""
          str << "+#{country_code}#{delimiter}" unless country_code.blank?
          str << if area_code
            number.gsub!(/([0-9]{1,3})([0-9]{3})([0-9]{4}$)/,"(\\1) \\2#{delimiter}\\3")
          else
44 45
            number.gsub!(/([0-9]{0,3})([0-9]{3})([0-9]{4})$/,"\\1#{delimiter}\\2#{delimiter}\\3")
            number.starts_with?('-') ? number.slice!(1..-1) : number
46 47 48
          end
          str << " x #{extension}" unless extension.blank?
          str
49 50 51 52 53
        rescue
          number
        end
      end

54
      # Formats a +number+ into a currency string (e.g., $13.65). You can customize the format
55 56
      # in the +options+ hash.
      #
57 58
      # ==== Options
      # * <tt>:precision</tt>  -  Sets the level of precision (defaults to 2).
59
      # * <tt>:unit</tt>       - Sets the denomination of the currency (defaults to "$").
60 61
      # * <tt>:separator</tt>  - Sets the separator between the units (defaults to ".").
      # * <tt>:delimiter</tt>  - Sets the thousands delimiter (defaults to ",").
62
      # * <tt>:format</tt>     - Sets the format of the output string (defaults to "%u%n"). The field types are:
63 64 65
      #
      #     %u  The currency unit
      #     %n  The number
66 67 68 69 70 71
      #
      # ==== Examples
      #  number_to_currency(1234567890.50)                    # => $1,234,567,890.50
      #  number_to_currency(1234567890.506)                   # => $1,234,567,890.51
      #  number_to_currency(1234567890.506, :precision => 3)  # => $1,234,567,890.506
      #
72
      #  number_to_currency(1234567890.50, :unit => "&pound;", :separator => ",", :delimiter => "")
73
      #  # => &pound;1234567890,50
74 75
      #  number_to_currency(1234567890.50, :unit => "&pound;", :separator => ",", :delimiter => "", :format => "%n %u")
      #  # => 1234567890,50 &pound;
76
      def number_to_currency(number, options = {})
77 78
        options.symbolize_keys!

79 80 81
        defaults  = I18n.translate(:'number.format', :locale => options[:locale], :raise => true) rescue {}
        currency  = I18n.translate(:'number.currency.format', :locale => options[:locale], :raise => true) rescue {}
        defaults  = defaults.merge(currency)
82

S
Sven Fuchs 已提交
83 84 85 86 87 88
        precision = options[:precision] || defaults[:precision]
        unit      = options[:unit]      || defaults[:unit]
        separator = options[:separator] || defaults[:separator]
        delimiter = options[:delimiter] || defaults[:delimiter]
        format    = options[:format]    || defaults[:format]
        separator = '' if precision == 0
89

90
        begin
91 92 93 94
          format.gsub(/%n/, number_with_precision(number,
            :precision => precision,
            :delimiter => delimiter,
            :separator => separator)
95
          ).gsub(/%u/, unit).html_safe
96 97 98 99 100
        rescue
          number
        end
      end

101
      # Formats a +number+ as a percentage string (e.g., 65%). You can customize the
102 103
      # format in the +options+ hash.
      #
104 105 106
      # ==== Options
      # * <tt>:precision</tt>  - Sets the level of precision (defaults to 3).
      # * <tt>:separator</tt>  - Sets the separator between the units (defaults to ".").
107
      # * <tt>:delimiter</tt>  - Sets the thousands delimiter (defaults to "").
108 109
      #
      # ==== Examples
110 111 112 113
      #  number_to_percentage(100)                                        # => 100.000%
      #  number_to_percentage(100, :precision => 0)                       # => 100%
      #  number_to_percentage(1000, :delimiter => '.', :separator => ',') # => 1.000,000%
      #  number_to_percentage(302.24398923423, :precision => 5)           # => 302.24399%
114
      def number_to_percentage(number, options = {})
115 116
        options.symbolize_keys!

117 118 119
        defaults   = I18n.translate(:'number.format', :locale => options[:locale], :raise => true) rescue {}
        percentage = I18n.translate(:'number.percentage.format', :locale => options[:locale], :raise => true) rescue {}
        defaults  = defaults.merge(percentage)
120 121 122 123

        precision = options[:precision] || defaults[:precision]
        separator = options[:separator] || defaults[:separator]
        delimiter = options[:delimiter] || defaults[:delimiter]
124

125
        begin
126 127 128 129
          number_with_precision(number,
            :precision => precision,
            :separator => separator,
            :delimiter => delimiter) + "%"
130 131 132 133 134
        rescue
          number
        end
      end

135 136
      # Formats a +number+ with grouped thousands using +delimiter+ (e.g., 12,324). You can
      # customize the format in the +options+ hash.
137
      #
138
      # ==== Options
139 140
      # * <tt>:delimiter</tt>  - Sets the thousands delimiter (defaults to ",").
      # * <tt>:separator</tt>  - Sets the separator between the units (defaults to ".").
141 142
      #
      # ==== Examples
143 144 145
      #  number_with_delimiter(12345678)                        # => 12,345,678
      #  number_with_delimiter(12345678.05)                     # => 12,345,678.05
      #  number_with_delimiter(12345678, :delimiter => ".")     # => 12.345.678
P
Pratik Naik 已提交
146
      #  number_with_delimiter(12345678, :separator => ",")     # => 12,345,678
147
      #  number_with_delimiter(98765432.98, :delimiter => " ", :separator => ",")
148
      #  # => 98 765 432,98
149 150 151 152
      #
      # You can still use <tt>number_with_delimiter</tt> with the old API that accepts the
      # +delimiter+ as its optional second and the +separator+ as its
      # optional third parameter:
153 154
      #  number_with_delimiter(12345678, " ")                     # => 12 345.678
      #  number_with_delimiter(12345678.05, ".", ",")             # => 12.345.678,05
155 156
      def number_with_delimiter(number, *args)
        options = args.extract_options!
157 158
        options.symbolize_keys!

159
        defaults = I18n.translate(:'number.format', :locale => options[:locale], :raise => true) rescue {}
160

161
        unless args.empty?
162 163 164 165
          ActiveSupport::Deprecation.warn('number_with_delimiter takes an option hash ' +
            'instead of separate delimiter and precision arguments.', caller)
          delimiter = args[0] || defaults[:delimiter]
          separator = args[1] || defaults[:separator]
166
        end
167 168 169

        delimiter ||= (options[:delimiter] || defaults[:delimiter])
        separator ||= (options[:separator] || defaults[:separator])
170

171
        begin
172
          parts = number.to_s.split('.')
173 174
          parts[0].gsub!(/(\d)(?=(\d\d\d)+(?!\d))/, "\\1#{delimiter}")
          parts.join(separator)
175 176 177
        rescue
          number
        end
178
      end
179

180
      # Formats a +number+ with the specified level of <tt>:precision</tt> (e.g., 112.32 has a precision of 2).
181 182 183 184 185 186
      # You can customize the format in the +options+ hash.
      #
      # ==== Options
      # * <tt>:precision</tt>  - Sets the level of precision (defaults to 3).
      # * <tt>:separator</tt>  - Sets the separator between the units (defaults to ".").
      # * <tt>:delimiter</tt>  - Sets the thousands delimiter (defaults to "").
187
      #
188
      # ==== Examples
189 190 191 192
      #  number_with_precision(111.2345)                    # => 111.235
      #  number_with_precision(111.2345, :precision => 2)   # => 111.23
      #  number_with_precision(13, :precision => 5)         # => 13.00000
      #  number_with_precision(389.32314, :precision => 0)  # => 389
193 194
      #  number_with_precision(1111.2345, :precision => 2, :separator => ',', :delimiter => '.')
      #  # => 1.111,23
195 196 197 198 199 200
      #
      # You can still use <tt>number_with_precision</tt> with the old API that accepts the
      # +precision+ as its optional second parameter:
      #   number_with_precision(number_with_precision(111.2345, 2)   # => 111.23
      def number_with_precision(number, *args)
        options = args.extract_options!
201 202
        options.symbolize_keys!

203 204 205 206
        defaults           = I18n.translate(:'number.format', :locale => options[:locale], :raise => true) rescue {}
        precision_defaults = I18n.translate(:'number.precision.format', :locale => options[:locale],
                                                                        :raise => true) rescue {}
        defaults           = defaults.merge(precision_defaults)
207

208
        unless args.empty?
209 210 211
          ActiveSupport::Deprecation.warn('number_with_precision takes an option hash ' +
            'instead of a separate precision argument.', caller)
          precision = args[0] || defaults[:precision]
212
        end
213 214 215 216 217

        precision ||= (options[:precision] || defaults[:precision])
        separator ||= (options[:separator] || defaults[:separator])
        delimiter ||= (options[:delimiter] || defaults[:delimiter])

218
        begin
219
          rounded_number = BigDecimal.new((Float(number) * (10 ** precision)).to_s).round.to_f / 10 ** precision
220 221 222 223 224 225
          number_with_delimiter("%01.#{precision}f" % rounded_number,
            :separator => separator,
            :delimiter => delimiter)
        rescue
          number
        end
226
      end
227

228 229
      STORAGE_UNITS = [:byte, :kb, :mb, :gb, :tb].freeze

230
      # Formats the bytes in +size+ into a more understandable representation
231
      # (e.g., giving it 1500 yields 1.5 KB). This method is useful for
232
      # reporting file sizes to users. This method returns nil if
233 234 235 236 237 238 239
      # +size+ cannot be converted into a number. You can customize the
      # format in the +options+ hash.
      #
      # ==== Options
      # * <tt>:precision</tt>  - Sets the level of precision (defaults to 1).
      # * <tt>:separator</tt>  - Sets the separator between the units (defaults to ".").
      # * <tt>:delimiter</tt>  - Sets the thousands delimiter (defaults to "").
240
      #
241
      # ==== Examples
242 243 244 245 246 247 248 249 250
      #  number_to_human_size(123)                                          # => 123 Bytes
      #  number_to_human_size(1234)                                         # => 1.2 KB
      #  number_to_human_size(12345)                                        # => 12.1 KB
      #  number_to_human_size(1234567)                                      # => 1.2 MB
      #  number_to_human_size(1234567890)                                   # => 1.1 GB
      #  number_to_human_size(1234567890123)                                # => 1.1 TB
      #  number_to_human_size(1234567, :precision => 2)                     # => 1.18 MB
      #  number_to_human_size(483989, :precision => 0)                      # => 473 KB
      #  number_to_human_size(1234567, :precision => 2, :separator => ',')  # => 1,18 MB
251
      #
252 253 254 255 256
      # Zeros after the decimal point are always stripped out, regardless of the
      # specified precision:
      #  helper.number_to_human_size(1234567890123, :precision => 5)        # => "1.12283 TB"
      #  helper.number_to_human_size(524288000, :precision=>5)              # => "500 MB"
      #
257 258
      # You can still use <tt>number_to_human_size</tt> with the old API that accepts the
      # +precision+ as its optional second parameter:
259
      #  number_to_human_size(1234567, 2)    # => 1.18 MB
260
      #  number_to_human_size(483989, 0)     # => 473 KB
261
      def number_to_human_size(number, *args)
262
        return nil if number.nil?
263

264
        options = args.extract_options!
265 266
        options.symbolize_keys!

267 268
        defaults = I18n.translate(:'number.format', :locale => options[:locale], :raise => true) rescue {}
        human    = I18n.translate(:'number.human.format', :locale => options[:locale], :raise => true) rescue {}
269 270
        defaults = defaults.merge(human)

271
        unless args.empty?
272 273 274
          ActiveSupport::Deprecation.warn('number_to_human_size takes an option hash ' +
            'instead of a separate precision argument.', caller)
          precision = args[0] || defaults[:precision]
275
        end
276 277 278 279 280

        precision ||= (options[:precision] || defaults[:precision])
        separator ||= (options[:separator] || defaults[:separator])
        delimiter ||= (options[:delimiter] || defaults[:delimiter])

281
        storage_units_format = I18n.translate(:'number.human.storage_units.format', :locale => options[:locale], :raise => true)
282

283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301
        if number.to_i < 1024
          unit = I18n.translate(:'number.human.storage_units.units.byte', :locale => options[:locale], :count => number.to_i, :raise => true)
          storage_units_format.gsub(/%n/, number.to_i.to_s).gsub(/%u/, unit)
        else
          max_exp  = STORAGE_UNITS.size - 1
          number   = Float(number)
          exponent = (Math.log(number) / Math.log(1024)).to_i # Convert to base 1024
          exponent = max_exp if exponent > max_exp # we need this to avoid overflow for the highest unit
          number  /= 1024 ** exponent

          unit_key = STORAGE_UNITS[exponent]
          unit = I18n.translate(:"number.human.storage_units.units.#{unit_key}", :locale => options[:locale], :count => number, :raise => true)

          begin
            escaped_separator = Regexp.escape(separator)
            formatted_number = number_with_precision(number,
              :precision => precision,
              :separator => separator,
              :delimiter => delimiter
302
            ).sub(/(#{escaped_separator})(\d*[1-9])?0+\z/, '\1\2').sub(/#{escaped_separator}\z/, '')
303 304 305 306
            storage_units_format.gsub(/%n/, formatted_number).gsub(/%u/, unit)
          rescue
            number
          end
307
        end
308
      end
309 310
    end
  end
311
end