PageRenderTime 55ms CodeModel.GetById 21ms RepoModel.GetById 0ms app.codeStats 0ms

/External.LCA_RESTRICTED/Languages/Ruby/ruby19/lib/ruby/gems/1.9.1/gems/actionpack-3.0.0/lib/action_view/helpers/number_helper.rb

http://github.com/IronLanguages/main
Ruby | 482 lines | 215 code | 50 blank | 217 comment | 24 complexity | b78ec3775a9cbbf4d0d7b434b0eb7f47 MD5 | raw file
Possible License(s): CPL-1.0, BSD-3-Clause, ISC, GPL-2.0, MPL-2.0-no-copyleft-exception
  1. require 'active_support/core_ext/big_decimal/conversions'
  2. require 'active_support/core_ext/float/rounding'
  3. require 'active_support/core_ext/object/blank'
  4. module ActionView
  5. # = Action View Number Helpers
  6. module Helpers #:nodoc:
  7. # Provides methods for converting numbers into formatted strings.
  8. # Methods are provided for phone numbers, currency, percentage,
  9. # precision, positional notation, file size and pretty printing.
  10. #
  11. # Most methods expect a +number+ argument, and will return it
  12. # unchanged if can't be converted into a valid number.
  13. module NumberHelper
  14. DEFAULT_CURRENCY_VALUES = { :format => "%u%n", :unit => "$", :separator => ".", :delimiter => ",",
  15. :precision => 2, :significant => false, :strip_insignificant_zeros => false }
  16. # Raised when argument +number+ param given to the helpers is invalid and
  17. # the option :raise is set to +true+.
  18. class InvalidNumberError < StandardError
  19. attr_accessor :number
  20. def initialize(number)
  21. @number = number
  22. end
  23. end
  24. # Formats a +number+ into a US phone number (e.g., (555) 123-9876). You can customize the format
  25. # in the +options+ hash.
  26. #
  27. # ==== Options
  28. # * <tt>:area_code</tt> - Adds parentheses around the area code.
  29. # * <tt>:delimiter</tt> - Specifies the delimiter to use (defaults to "-").
  30. # * <tt>:extension</tt> - Specifies an extension to add to the end of the
  31. # generated number.
  32. # * <tt>:country_code</tt> - Sets the country code for the phone number.
  33. #
  34. # ==== Examples
  35. # number_to_phone(5551234) # => 555-1234
  36. # number_to_phone(1235551234) # => 123-555-1234
  37. # number_to_phone(1235551234, :area_code => true) # => (123) 555-1234
  38. # number_to_phone(1235551234, :delimiter => " ") # => 123 555 1234
  39. # number_to_phone(1235551234, :area_code => true, :extension => 555) # => (123) 555-1234 x 555
  40. # number_to_phone(1235551234, :country_code => 1) # => +1-123-555-1234
  41. #
  42. # number_to_phone(1235551234, :country_code => 1, :extension => 1343, :delimiter => ".")
  43. # => +1.123.555.1234 x 1343
  44. def number_to_phone(number, options = {})
  45. return nil if number.nil?
  46. begin
  47. Float(number)
  48. is_number_html_safe = true
  49. rescue ArgumentError, TypeError
  50. if options[:raise]
  51. raise InvalidNumberError, number
  52. else
  53. is_number_html_safe = number.to_s.html_safe?
  54. end
  55. end
  56. number = number.to_s.strip
  57. options = options.symbolize_keys
  58. area_code = options[:area_code] || nil
  59. delimiter = options[:delimiter] || "-"
  60. extension = options[:extension].to_s.strip || nil
  61. country_code = options[:country_code] || nil
  62. str = ""
  63. str << "+#{country_code}#{delimiter}" unless country_code.blank?
  64. str << if area_code
  65. number.gsub!(/([0-9]{1,3})([0-9]{3})([0-9]{4}$)/,"(\\1) \\2#{delimiter}\\3")
  66. else
  67. number.gsub!(/([0-9]{0,3})([0-9]{3})([0-9]{4})$/,"\\1#{delimiter}\\2#{delimiter}\\3")
  68. number.starts_with?('-') ? number.slice!(1..-1) : number
  69. end
  70. str << " x #{extension}" unless extension.blank?
  71. is_number_html_safe ? str.html_safe : str
  72. end
  73. # Formats a +number+ into a currency string (e.g., $13.65). You can customize the format
  74. # in the +options+ hash.
  75. #
  76. # ==== Options
  77. # * <tt>:locale</tt> - Sets the locale to be used for formatting (defaults to current locale).
  78. # * <tt>:precision</tt> - Sets the level of precision (defaults to 2).
  79. # * <tt>:unit</tt> - Sets the denomination of the currency (defaults to "$").
  80. # * <tt>:separator</tt> - Sets the separator between the units (defaults to ".").
  81. # * <tt>:delimiter</tt> - Sets the thousands delimiter (defaults to ",").
  82. # * <tt>:format</tt> - Sets the format of the output string (defaults to "%u%n"). The field types are:
  83. #
  84. # %u The currency unit
  85. # %n The number
  86. #
  87. # ==== Examples
  88. # number_to_currency(1234567890.50) # => $1,234,567,890.50
  89. # number_to_currency(1234567890.506) # => $1,234,567,890.51
  90. # number_to_currency(1234567890.506, :precision => 3) # => $1,234,567,890.506
  91. # number_to_currency(1234567890.506, :locale => :fr) # => 1 234 567 890,506 €
  92. #
  93. # number_to_currency(1234567890.50, :unit => "&pound;", :separator => ",", :delimiter => "")
  94. # # => &pound;1234567890,50
  95. # number_to_currency(1234567890.50, :unit => "&pound;", :separator => ",", :delimiter => "", :format => "%n %u")
  96. # # => 1234567890,50 &pound;
  97. def number_to_currency(number, options = {})
  98. return nil if number.nil?
  99. options.symbolize_keys!
  100. defaults = I18n.translate(:'number.format', :locale => options[:locale], :default => {})
  101. currency = I18n.translate(:'number.currency.format', :locale => options[:locale], :default => {})
  102. defaults = DEFAULT_CURRENCY_VALUES.merge(defaults).merge!(currency)
  103. options = defaults.merge!(options)
  104. unit = options.delete(:unit)
  105. format = options.delete(:format)
  106. begin
  107. value = number_with_precision(number, options.merge(:raise => true))
  108. format.gsub(/%n/, value).gsub(/%u/, unit).html_safe
  109. rescue InvalidNumberError => e
  110. if options[:raise]
  111. raise
  112. else
  113. formatted_number = format.gsub(/%n/, e.number).gsub(/%u/, unit)
  114. e.number.to_s.html_safe? ? formatted_number.html_safe : formatted_number
  115. end
  116. end
  117. end
  118. # Formats a +number+ as a percentage string (e.g., 65%). You can customize the
  119. # format in the +options+ hash.
  120. #
  121. # ==== Options
  122. # * <tt>:locale</tt> - Sets the locale to be used for formatting (defaults to current locale).
  123. # * <tt>:precision</tt> - Sets the precision of the number (defaults to 3).
  124. # * <tt>:significant</tt> - If +true+, precision will be the # of significant_digits. If +false+, the # of fractional digits (defaults to +false+)
  125. # * <tt>:separator</tt> - Sets the separator between the fractional and integer digits (defaults to ".").
  126. # * <tt>:delimiter</tt> - Sets the thousands delimiter (defaults to "").
  127. # * <tt>:strip_insignificant_zeros</tt> - If +true+ removes insignificant zeros after the decimal separator (defaults to +false+)
  128. #
  129. # ==== Examples
  130. # number_to_percentage(100) # => 100.000%
  131. # number_to_percentage(100, :precision => 0) # => 100%
  132. # number_to_percentage(1000, :delimiter => '.', :separator => ',') # => 1.000,000%
  133. # number_to_percentage(302.24398923423, :precision => 5) # => 302.24399%
  134. # number_to_percentage(1000, :locale => :fr) # => 1 000,000%
  135. def number_to_percentage(number, options = {})
  136. return nil if number.nil?
  137. options.symbolize_keys!
  138. defaults = I18n.translate(:'number.format', :locale => options[:locale], :default => {})
  139. percentage = I18n.translate(:'number.percentage.format', :locale => options[:locale], :default => {})
  140. defaults = defaults.merge(percentage)
  141. options = options.reverse_merge(defaults)
  142. begin
  143. "#{number_with_precision(number, options.merge(:raise => true))}%".html_safe
  144. rescue InvalidNumberError => e
  145. if options[:raise]
  146. raise
  147. else
  148. e.number.to_s.html_safe? ? "#{e.number}%".html_safe : "#{e.number}%"
  149. end
  150. end
  151. end
  152. # Formats a +number+ with grouped thousands using +delimiter+ (e.g., 12,324). You can
  153. # customize the format in the +options+ hash.
  154. #
  155. # ==== Options
  156. # * <tt>:locale</tt> - Sets the locale to be used for formatting (defaults to current locale).
  157. # * <tt>:delimiter</tt> - Sets the thousands delimiter (defaults to ",").
  158. # * <tt>:separator</tt> - Sets the separator between the fractional and integer digits (defaults to ".").
  159. #
  160. # ==== Examples
  161. # number_with_delimiter(12345678) # => 12,345,678
  162. # number_with_delimiter(12345678.05) # => 12,345,678.05
  163. # number_with_delimiter(12345678, :delimiter => ".") # => 12.345.678
  164. # number_with_delimiter(12345678, :separator => ",") # => 12,345,678
  165. # number_with_delimiter(12345678.05, :locale => :fr) # => 12 345 678,05
  166. # number_with_delimiter(98765432.98, :delimiter => " ", :separator => ",")
  167. # # => 98 765 432,98
  168. def number_with_delimiter(number, options = {})
  169. options.symbolize_keys!
  170. begin
  171. Float(number)
  172. rescue ArgumentError, TypeError
  173. if options[:raise]
  174. raise InvalidNumberError, number
  175. else
  176. return number
  177. end
  178. end
  179. defaults = I18n.translate(:'number.format', :locale => options[:locale], :default => {})
  180. options = options.reverse_merge(defaults)
  181. parts = number.to_s.split('.')
  182. parts[0].gsub!(/(\d)(?=(\d\d\d)+(?!\d))/, "\\1#{options[:delimiter]}")
  183. parts.join(options[:separator]).html_safe
  184. end
  185. # Formats a +number+ with the specified level of <tt>:precision</tt> (e.g., 112.32 has a precision
  186. # of 2 if +:significant+ is +false+, and 5 if +:significant+ is +true+).
  187. # You can customize the format in the +options+ hash.
  188. #
  189. # ==== Options
  190. # * <tt>:locale</tt> - Sets the locale to be used for formatting (defaults to current locale).
  191. # * <tt>:precision</tt> - Sets the precision of the number (defaults to 3).
  192. # * <tt>:significant</tt> - If +true+, precision will be the # of significant_digits. If +false+, the # of fractional digits (defaults to +false+)
  193. # * <tt>:separator</tt> - Sets the separator between the fractional and integer digits (defaults to ".").
  194. # * <tt>:delimiter</tt> - Sets the thousands delimiter (defaults to "").
  195. # * <tt>:strip_insignificant_zeros</tt> - If +true+ removes insignificant zeros after the decimal separator (defaults to +false+)
  196. #
  197. # ==== Examples
  198. # number_with_precision(111.2345) # => 111.235
  199. # number_with_precision(111.2345, :precision => 2) # => 111.23
  200. # number_with_precision(13, :precision => 5) # => 13.00000
  201. # number_with_precision(389.32314, :precision => 0) # => 389
  202. # number_with_precision(111.2345, :significant => true) # => 111
  203. # number_with_precision(111.2345, :precision => 1, :significant => true) # => 100
  204. # number_with_precision(13, :precision => 5, :significant => true) # => 13.000
  205. # number_with_precision(111.234, :locale => :fr) # => 111,234
  206. # number_with_precision(13, :precision => 5, :significant => true, strip_insignificant_zeros => true)
  207. # # => 13
  208. # number_with_precision(389.32314, :precision => 4, :significant => true) # => 389.3
  209. # number_with_precision(1111.2345, :precision => 2, :separator => ',', :delimiter => '.')
  210. # # => 1.111,23
  211. def number_with_precision(number, options = {})
  212. options.symbolize_keys!
  213. number = begin
  214. Float(number)
  215. rescue ArgumentError, TypeError
  216. if options[:raise]
  217. raise InvalidNumberError, number
  218. else
  219. return number
  220. end
  221. end
  222. defaults = I18n.translate(:'number.format', :locale => options[:locale], :default => {})
  223. precision_defaults = I18n.translate(:'number.precision.format', :locale => options[:locale], :default => {})
  224. defaults = defaults.merge(precision_defaults)
  225. options = options.reverse_merge(defaults) # Allow the user to unset default values: Eg.: :significant => false
  226. precision = options.delete :precision
  227. significant = options.delete :significant
  228. strip_insignificant_zeros = options.delete :strip_insignificant_zeros
  229. if significant and precision > 0
  230. if number == 0
  231. digits, rounded_number = 1, 0
  232. else
  233. digits = (Math.log10(number) + 1).floor
  234. rounded_number = BigDecimal.new((number / 10 ** (digits - precision)).to_s).round.to_f * 10 ** (digits - precision)
  235. end
  236. precision = precision - digits
  237. precision = precision > 0 ? precision : 0 #don't let it be negative
  238. else
  239. rounded_number = BigDecimal.new((number * (10 ** precision)).to_s).round.to_f / 10 ** precision
  240. end
  241. formatted_number = number_with_delimiter("%01.#{precision}f" % rounded_number, options)
  242. if strip_insignificant_zeros
  243. escaped_separator = Regexp.escape(options[:separator])
  244. formatted_number.sub(/(#{escaped_separator})(\d*[1-9])?0+\z/, '\1\2').sub(/#{escaped_separator}\z/, '').html_safe
  245. else
  246. formatted_number
  247. end
  248. end
  249. STORAGE_UNITS = [:byte, :kb, :mb, :gb, :tb].freeze
  250. # Formats the bytes in +number+ into a more understandable representation
  251. # (e.g., giving it 1500 yields 1.5 KB). This method is useful for
  252. # reporting file sizes to users. You can customize the
  253. # format in the +options+ hash.
  254. #
  255. # See <tt>number_to_human</tt> if you want to pretty-print a generic number.
  256. #
  257. # ==== Options
  258. # * <tt>:locale</tt> - Sets the locale to be used for formatting (defaults to current locale).
  259. # * <tt>:precision</tt> - Sets the precision of the number (defaults to 3).
  260. # * <tt>:significant</tt> - If +true+, precision will be the # of significant_digits. If +false+, the # of fractional digits (defaults to +true+)
  261. # * <tt>:separator</tt> - Sets the separator between the fractional and integer digits (defaults to ".").
  262. # * <tt>:delimiter</tt> - Sets the thousands delimiter (defaults to "").
  263. # * <tt>:strip_insignificant_zeros</tt> - If +true+ removes insignificant zeros after the decimal separator (defaults to +true+)
  264. # ==== Examples
  265. # number_to_human_size(123) # => 123 Bytes
  266. # number_to_human_size(1234) # => 1.21 KB
  267. # number_to_human_size(12345) # => 12.1 KB
  268. # number_to_human_size(1234567) # => 1.18 MB
  269. # number_to_human_size(1234567890) # => 1.15 GB
  270. # number_to_human_size(1234567890123) # => 1.12 TB
  271. # number_to_human_size(1234567, :precision => 2) # => 1.2 MB
  272. # number_to_human_size(483989, :precision => 2) # => 470 KB
  273. # number_to_human_size(1234567, :precision => 2, :separator => ',') # => 1,2 MB
  274. #
  275. # Non-significant zeros after the fractional separator are stripped out by default (set
  276. # <tt>:strip_insignificant_zeros</tt> to +false+ to change that):
  277. # number_to_human_size(1234567890123, :precision => 5) # => "1.1229 TB"
  278. # number_to_human_size(524288000, :precision=>5) # => "500 MB"
  279. def number_to_human_size(number, options = {})
  280. options.symbolize_keys!
  281. number = begin
  282. Float(number)
  283. rescue ArgumentError, TypeError
  284. if options[:raise]
  285. raise InvalidNumberError, number
  286. else
  287. return number
  288. end
  289. end
  290. defaults = I18n.translate(:'number.format', :locale => options[:locale], :default => {})
  291. human = I18n.translate(:'number.human.format', :locale => options[:locale], :default => {})
  292. defaults = defaults.merge(human)
  293. options = options.reverse_merge(defaults)
  294. #for backwards compatibility with those that didn't add strip_insignificant_zeros to their locale files
  295. options[:strip_insignificant_zeros] = true if not options.key?(:strip_insignificant_zeros)
  296. storage_units_format = I18n.translate(:'number.human.storage_units.format', :locale => options[:locale], :raise => true)
  297. if number.to_i < 1024
  298. unit = I18n.translate(:'number.human.storage_units.units.byte', :locale => options[:locale], :count => number.to_i, :raise => true)
  299. storage_units_format.gsub(/%n/, number.to_i.to_s).gsub(/%u/, unit).html_safe
  300. else
  301. max_exp = STORAGE_UNITS.size - 1
  302. exponent = (Math.log(number) / Math.log(1024)).to_i # Convert to base 1024
  303. exponent = max_exp if exponent > max_exp # we need this to avoid overflow for the highest unit
  304. number /= 1024 ** exponent
  305. unit_key = STORAGE_UNITS[exponent]
  306. unit = I18n.translate(:"number.human.storage_units.units.#{unit_key}", :locale => options[:locale], :count => number, :raise => true)
  307. formatted_number = number_with_precision(number, options)
  308. storage_units_format.gsub(/%n/, formatted_number).gsub(/%u/, unit).html_safe
  309. end
  310. end
  311. DECIMAL_UNITS = {0 => :unit, 1 => :ten, 2 => :hundred, 3 => :thousand, 6 => :million, 9 => :billion, 12 => :trillion, 15 => :quadrillion,
  312. -1 => :deci, -2 => :centi, -3 => :mili, -6 => :micro, -9 => :nano, -12 => :pico, -15 => :femto}.freeze
  313. # Pretty prints (formats and approximates) a number in a way it is more readable by humans
  314. # (eg.: 1200000000 becomes "1.2 Billion"). This is useful for numbers that
  315. # can get very large (and too hard to read).
  316. #
  317. # See <tt>number_to_human_size</tt> if you want to print a file size.
  318. #
  319. # You can also define you own unit-quantifier names if you want to use other decimal units
  320. # (eg.: 1500 becomes "1.5 kilometers", 0.150 becomes "150 mililiters", etc). You may define
  321. # a wide range of unit quantifiers, even fractional ones (centi, deci, mili, etc).
  322. #
  323. # ==== Options
  324. # * <tt>:locale</tt> - Sets the locale to be used for formatting (defaults to current locale).
  325. # * <tt>:precision</tt> - Sets the precision of the number (defaults to 3).
  326. # * <tt>:significant</tt> - If +true+, precision will be the # of significant_digits. If +false+, the # of fractional digits (defaults to +true+)
  327. # * <tt>:separator</tt> - Sets the separator between the fractional and integer digits (defaults to ".").
  328. # * <tt>:delimiter</tt> - Sets the thousands delimiter (defaults to "").
  329. # * <tt>:strip_insignificant_zeros</tt> - If +true+ removes insignificant zeros after the decimal separator (defaults to +true+)
  330. # * <tt>:units</tt> - A Hash of unit quantifier names. Or a string containing an i18n scope where to find this hash. It might have the following keys:
  331. # * *integers*: <tt>:unit</tt>, <tt>:ten</tt>, <tt>:hundred</tt>, <tt>:thousand</tt>, <tt>:million</tt>, <tt>:billion</tt>, <tt>:trillion</tt>, <tt>:quadrillion</tt>
  332. # * *fractionals*: <tt>:deci</tt>, <tt>:centi</tt>, <tt>:mili</tt>, <tt>:micro</tt>, <tt>:nano</tt>, <tt>:pico</tt>, <tt>:femto</tt>
  333. # * <tt>:format</tt> - Sets the format of the output string (defaults to "%n %u"). The field types are:
  334. #
  335. # %u The quantifier (ex.: 'thousand')
  336. # %n The number
  337. #
  338. # ==== Examples
  339. # number_to_human(123) # => "123"
  340. # number_to_human(1234) # => "1.23 Thousand"
  341. # number_to_human(12345) # => "12.3 Thousand"
  342. # number_to_human(1234567) # => "1.23 Million"
  343. # number_to_human(1234567890) # => "1.23 Billion"
  344. # number_to_human(1234567890123) # => "1.23 Trillion"
  345. # number_to_human(1234567890123456) # => "1.23 Quadrillion"
  346. # number_to_human(1234567890123456789) # => "1230 Quadrillion"
  347. # number_to_human(489939, :precision => 2) # => "490 Thousand"
  348. # number_to_human(489939, :precision => 4) # => "489.9 Thousand"
  349. # number_to_human(1234567, :precision => 4,
  350. # :significant => false) # => "1.2346 Million"
  351. # number_to_human(1234567, :precision => 1,
  352. # :separator => ',',
  353. # :significant => false) # => "1,2 Million"
  354. #
  355. # Unsignificant zeros after the decimal separator are stripped out by default (set
  356. # <tt>:strip_insignificant_zeros</tt> to +false+ to change that):
  357. # number_to_human(12345012345, :significant_digits => 6) # => "12.345 Billion"
  358. # number_to_human(500000000, :precision=>5) # => "500 Million"
  359. #
  360. # ==== Custom Unit Quantifiers
  361. #
  362. # You can also use your own custom unit quantifiers:
  363. # number_to_human(500000, :units => {:unit => "ml", :thousand => "lt"}) # => "500 lt"
  364. #
  365. # If in your I18n locale you have:
  366. # distance:
  367. # centi:
  368. # one: "centimeter"
  369. # other: "centimeters"
  370. # unit:
  371. # one: "meter"
  372. # other: "meters"
  373. # thousand:
  374. # one: "kilometer"
  375. # other: "kilometers"
  376. # billion: "gazilion-distance"
  377. #
  378. # Then you could do:
  379. #
  380. # number_to_human(543934, :units => :distance) # => "544 kilometers"
  381. # number_to_human(54393498, :units => :distance) # => "54400 kilometers"
  382. # number_to_human(54393498000, :units => :distance) # => "54.4 gazilion-distance"
  383. # number_to_human(343, :units => :distance, :precision => 1) # => "300 meters"
  384. # number_to_human(1, :units => :distance) # => "1 meter"
  385. # number_to_human(0.34, :units => :distance) # => "34 centimeters"
  386. #
  387. def number_to_human(number, options = {})
  388. options.symbolize_keys!
  389. number = begin
  390. Float(number)
  391. rescue ArgumentError, TypeError
  392. if options[:raise]
  393. raise InvalidNumberError, number
  394. else
  395. return number
  396. end
  397. end
  398. defaults = I18n.translate(:'number.format', :locale => options[:locale], :default => {})
  399. human = I18n.translate(:'number.human.format', :locale => options[:locale], :default => {})
  400. defaults = defaults.merge(human)
  401. options = options.reverse_merge(defaults)
  402. #for backwards compatibility with those that didn't add strip_insignificant_zeros to their locale files
  403. options[:strip_insignificant_zeros] = true if not options.key?(:strip_insignificant_zeros)
  404. units = options.delete :units
  405. unit_exponents = case units
  406. when Hash
  407. units
  408. when String, Symbol
  409. I18n.translate(:"#{units}", :locale => options[:locale], :raise => true)
  410. when nil
  411. I18n.translate(:"number.human.decimal_units.units", :locale => options[:locale], :raise => true)
  412. else
  413. raise ArgumentError, ":units must be a Hash or String translation scope."
  414. end.keys.map{|e_name| DECIMAL_UNITS.invert[e_name] }.sort_by{|e| -e}
  415. number_exponent = Math.log10(number).floor
  416. display_exponent = unit_exponents.find{|e| number_exponent >= e }
  417. number /= 10 ** display_exponent
  418. unit = case units
  419. when Hash
  420. units[DECIMAL_UNITS[display_exponent]]
  421. when String, Symbol
  422. I18n.translate(:"#{units}.#{DECIMAL_UNITS[display_exponent]}", :locale => options[:locale], :count => number.to_i)
  423. else
  424. I18n.translate(:"number.human.decimal_units.units.#{DECIMAL_UNITS[display_exponent]}", :locale => options[:locale], :count => number.to_i)
  425. end
  426. decimal_format = options[:format] || I18n.translate(:'number.human.decimal_units.format', :locale => options[:locale], :default => "%n %u")
  427. formatted_number = number_with_precision(number, options)
  428. decimal_format.gsub(/%n/, formatted_number).gsub(/%u/, unit).strip.html_safe
  429. end
  430. end
  431. end
  432. end