PageRenderTime 58ms CodeModel.GetById 17ms RepoModel.GetById 0ms app.codeStats 1ms

/vendor/bundle/ruby/1.9.1/gems/actionpack-3.2.2/lib/action_view/helpers/number_helper.rb

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