PageRenderTime 56ms CodeModel.GetById 25ms RepoModel.GetById 0ms app.codeStats 1ms

/activesupport/lib/active_support/number_helper.rb

https://bitbucket.org/rrmartins/rails
Ruby | 636 lines | 247 code | 54 blank | 335 comment | 26 complexity | 9b8aa3fd7d493f5f5329baa6937fec2c MD5 | raw file
  1. require 'active_support/core_ext/big_decimal/conversions'
  2. require 'active_support/core_ext/object/blank'
  3. require 'active_support/core_ext/hash/keys'
  4. require 'active_support/i18n'
  5. module ActiveSupport
  6. module NumberHelper
  7. extend self
  8. DEFAULTS = {
  9. # Used in number_to_delimited
  10. # These are also the defaults for 'currency', 'percentage', 'precision', and 'human'
  11. format: {
  12. # Sets the separator between the units, for more precision (e.g. 1.0 / 2.0 == 0.5)
  13. separator: ".",
  14. # Delimits thousands (e.g. 1,000,000 is a million) (always in groups of three)
  15. delimiter: ",",
  16. # Number of decimals, behind the separator (the number 1 with a precision of 2 gives: 1.00)
  17. precision: 3,
  18. # If set to true, precision will mean the number of significant digits instead
  19. # of the number of decimal digits (1234 with precision 2 becomes 1200, 1.23543 becomes 1.2)
  20. significant: false,
  21. # If set, the zeros after the decimal separator will always be stripped (eg.: 1.200 will be 1.2)
  22. strip_insignificant_zeros: false
  23. },
  24. # Used in number_to_currency
  25. currency: {
  26. format: {
  27. format: "%u%n",
  28. negative_format: "-%u%n",
  29. unit: "$",
  30. # These five are to override number.format and are optional
  31. separator: ".",
  32. delimiter: ",",
  33. precision: 2,
  34. significant: false,
  35. strip_insignificant_zeros: false
  36. }
  37. },
  38. # Used in number_to_percentage
  39. percentage: {
  40. format: {
  41. delimiter: "",
  42. format: "%n%"
  43. }
  44. },
  45. # Used in number_to_rounded
  46. precision: {
  47. format: {
  48. delimiter: ""
  49. }
  50. },
  51. # Used in number_to_human_size and number_to_human
  52. human: {
  53. format: {
  54. # These five are to override number.format and are optional
  55. delimiter: "",
  56. precision: 3,
  57. significant: true,
  58. strip_insignificant_zeros: true
  59. },
  60. # Used in number_to_human_size
  61. storage_units: {
  62. # Storage units output formatting.
  63. # %u is the storage unit, %n is the number (default: 2 MB)
  64. format: "%n %u",
  65. units: {
  66. byte: "Bytes",
  67. kb: "KB",
  68. mb: "MB",
  69. gb: "GB",
  70. tb: "TB"
  71. }
  72. },
  73. # Used in number_to_human
  74. decimal_units: {
  75. format: "%n %u",
  76. # Decimal units output formatting
  77. # By default we will only quantify some of the exponents
  78. # but the commented ones might be defined or overridden
  79. # by the user.
  80. units: {
  81. # femto: Quadrillionth
  82. # pico: Trillionth
  83. # nano: Billionth
  84. # micro: Millionth
  85. # mili: Thousandth
  86. # centi: Hundredth
  87. # deci: Tenth
  88. unit: "",
  89. # ten:
  90. # one: Ten
  91. # other: Tens
  92. # hundred: Hundred
  93. thousand: "Thousand",
  94. million: "Million",
  95. billion: "Billion",
  96. trillion: "Trillion",
  97. quadrillion: "Quadrillion"
  98. }
  99. }
  100. }
  101. }
  102. DECIMAL_UNITS = { 0 => :unit, 1 => :ten, 2 => :hundred, 3 => :thousand, 6 => :million, 9 => :billion, 12 => :trillion, 15 => :quadrillion,
  103. -1 => :deci, -2 => :centi, -3 => :mili, -6 => :micro, -9 => :nano, -12 => :pico, -15 => :femto }
  104. STORAGE_UNITS = [:byte, :kb, :mb, :gb, :tb]
  105. # Formats a +number+ into a US phone number (e.g., (555)
  106. # 123-9876). You can customize the format in the +options+ hash.
  107. #
  108. # ==== Options
  109. #
  110. # * <tt>:area_code</tt> - Adds parentheses around the area code.
  111. # * <tt>:delimiter</tt> - Specifies the delimiter to use
  112. # (defaults to "-").
  113. # * <tt>:extension</tt> - Specifies an extension to add to the
  114. # end of the generated number.
  115. # * <tt>:country_code</tt> - Sets the country code for the phone
  116. # number.
  117. # ==== Examples
  118. #
  119. # number_to_phone(5551234) # => 555-1234
  120. # number_to_phone('5551234') # => 555-1234
  121. # number_to_phone(1235551234) # => 123-555-1234
  122. # number_to_phone(1235551234, area_code: true) # => (123) 555-1234
  123. # number_to_phone(1235551234, delimiter: ' ') # => 123 555 1234
  124. # number_to_phone(1235551234, area_code: true, extension: 555) # => (123) 555-1234 x 555
  125. # number_to_phone(1235551234, country_code: 1) # => +1-123-555-1234
  126. # number_to_phone('123a456') # => 123a456
  127. #
  128. # number_to_phone(1235551234, country_code: 1, extension: 1343, delimiter: '.')
  129. # # => +1.123.555.1234 x 1343
  130. def number_to_phone(number, options = {})
  131. return unless number
  132. options = options.symbolize_keys
  133. number = number.to_s.strip
  134. area_code = options[:area_code]
  135. delimiter = options[:delimiter] || "-"
  136. extension = options[:extension]
  137. country_code = options[:country_code]
  138. if area_code
  139. number.gsub!(/(\d{1,3})(\d{3})(\d{4}$)/,"(\\1) \\2#{delimiter}\\3")
  140. else
  141. number.gsub!(/(\d{0,3})(\d{3})(\d{4})$/,"\\1#{delimiter}\\2#{delimiter}\\3")
  142. number.slice!(0, 1) if number.start_with?(delimiter) && !delimiter.blank?
  143. end
  144. str = ''
  145. str << "+#{country_code}#{delimiter}" unless country_code.blank?
  146. str << number
  147. str << " x #{extension}" unless extension.blank?
  148. str
  149. end
  150. # Formats a +number+ into a currency string (e.g., $13.65). You
  151. # can customize the format in the +options+ hash.
  152. #
  153. # ==== Options
  154. #
  155. # * <tt>:locale</tt> - Sets the locale to be used for formatting
  156. # (defaults to current locale).
  157. # * <tt>:precision</tt> - Sets the level of precision (defaults
  158. # to 2).
  159. # * <tt>:unit</tt> - Sets the denomination of the currency
  160. # (defaults to "$").
  161. # * <tt>:separator</tt> - Sets the separator between the units
  162. # (defaults to ".").
  163. # * <tt>:delimiter</tt> - Sets the thousands delimiter (defaults
  164. # to ",").
  165. # * <tt>:format</tt> - Sets the format for non-negative numbers
  166. # (defaults to "%u%n"). Fields are <tt>%u</tt> for the
  167. # currency, and <tt>%n</tt> for the number.
  168. # * <tt>:negative_format</tt> - Sets the format for negative
  169. # numbers (defaults to prepending an hyphen to the formatted
  170. # number given by <tt>:format</tt>). Accepts the same fields
  171. # than <tt>:format</tt>, except <tt>%n</tt> is here the
  172. # absolute value of the number.
  173. #
  174. # ==== Examples
  175. #
  176. # number_to_currency(1234567890.50) # => $1,234,567,890.50
  177. # number_to_currency(1234567890.506) # => $1,234,567,890.51
  178. # number_to_currency(1234567890.506, precision: 3) # => $1,234,567,890.506
  179. # number_to_currency(1234567890.506, locale: :fr) # => 1 234 567 890,51
  180. # number_to_currency('123a456') # => $123a456
  181. #
  182. # number_to_currency(-1234567890.50, negative_format: '(%u%n)')
  183. # # => ($1,234,567,890.50)
  184. # number_to_currency(1234567890.50, unit: '&pound;', separator: ',', delimiter: '')
  185. # # => &pound;1234567890,50
  186. # number_to_currency(1234567890.50, unit: '&pound;', separator: ',', delimiter: '', format: '%n %u')
  187. # # => 1234567890,50 &pound;
  188. def number_to_currency(number, options = {})
  189. return unless number
  190. options = options.symbolize_keys
  191. currency = i18n_format_options(options[:locale], :currency)
  192. currency[:negative_format] ||= "-" + currency[:format] if currency[:format]
  193. defaults = default_format_options(:currency).merge!(currency)
  194. defaults[:negative_format] = "-" + options[:format] if options[:format]
  195. options = defaults.merge!(options)
  196. unit = options.delete(:unit)
  197. format = options.delete(:format)
  198. if number.to_f.phase != 0
  199. format = options.delete(:negative_format)
  200. number = number.respond_to?("abs") ? number.abs : number.sub(/^-/, '')
  201. end
  202. format.gsub('%n', self.number_to_rounded(number, options)).gsub('%u', unit)
  203. end
  204. # Formats a +number+ as a percentage string (e.g., 65%). You can
  205. # customize the format in the +options+ hash.
  206. #
  207. # ==== Options
  208. #
  209. # * <tt>:locale</tt> - Sets the locale to be used for formatting
  210. # (defaults to current locale).
  211. # * <tt>:precision</tt> - Sets the precision of the number
  212. # (defaults to 3).
  213. # * <tt>:significant</tt> - If +true+, precision will be the #
  214. # of significant_digits. If +false+, the # of fractional
  215. # digits (defaults to +false+).
  216. # * <tt>:separator</tt> - Sets the separator between the
  217. # fractional and integer digits (defaults to ".").
  218. # * <tt>:delimiter</tt> - Sets the thousands delimiter (defaults
  219. # to "").
  220. # * <tt>:strip_insignificant_zeros</tt> - If +true+ removes
  221. # insignificant zeros after the decimal separator (defaults to
  222. # +false+).
  223. # * <tt>:format</tt> - Specifies the format of the percentage
  224. # string The number field is <tt>%n</tt> (defaults to "%n%").
  225. #
  226. # ==== Examples
  227. #
  228. # number_to_percentage(100) # => 100.000%
  229. # number_to_percentage('98') # => 98.000%
  230. # number_to_percentage(100, precision: 0) # => 100%
  231. # number_to_percentage(1000, delimiter: '.', separator: ,') # => 1.000,000%
  232. # number_to_percentage(302.24398923423, precision: 5) # => 302.24399%
  233. # number_to_percentage(1000, locale: :fr) # => 1 000,000%
  234. # number_to_percentage('98a') # => 98a%
  235. # number_to_percentage(100, format: '%n %') # => 100 %
  236. def number_to_percentage(number, options = {})
  237. return unless number
  238. options = options.symbolize_keys
  239. defaults = format_options(options[:locale], :percentage)
  240. options = defaults.merge!(options)
  241. format = options[:format] || "%n%"
  242. format.gsub('%n', self.number_to_rounded(number, options))
  243. end
  244. # Formats a +number+ with grouped thousands using +delimiter+
  245. # (e.g., 12,324). You can customize the format in the +options+
  246. # hash.
  247. #
  248. # ==== Options
  249. #
  250. # * <tt>:locale</tt> - Sets the locale to be used for formatting
  251. # (defaults to current locale).
  252. # * <tt>:delimiter</tt> - Sets the thousands delimiter (defaults
  253. # to ",").
  254. # * <tt>:separator</tt> - Sets the separator between the
  255. # fractional and integer digits (defaults to ".").
  256. #
  257. # ==== Examples
  258. #
  259. # number_to_delimited(12345678) # => 12,345,678
  260. # number_to_delimited('123456') # => 123,456
  261. # number_to_delimited(12345678.05) # => 12,345,678.05
  262. # number_to_delimited(12345678, delimiter: '.') # => 12.345.678
  263. # number_to_delimited(12345678, delimiter: ',') # => 12,345,678
  264. # number_to_delimited(12345678.05, separator: ' ') # => 12,345,678 05
  265. # number_to_delimited(12345678.05, locale: :fr) # => 12 345 678,05
  266. # number_to_delimited('112a') # => 112a
  267. # number_to_delimited(98765432.98, delimiter: ' ', separator: ',')
  268. # # => 98 765 432,98
  269. def number_to_delimited(number, options = {})
  270. options = options.symbolize_keys
  271. return number unless valid_float?(number)
  272. options = format_options(options[:locale]).merge!(options)
  273. parts = number.to_s.to_str.split('.')
  274. parts[0].gsub!(/(\d)(?=(\d\d\d)+(?!\d))/, "\\1#{options[:delimiter]}")
  275. parts.join(options[:separator])
  276. end
  277. # Formats a +number+ with the specified level of
  278. # <tt>:precision</tt> (e.g., 112.32 has a precision of 2 if
  279. # +:significant+ is +false+, and 5 if +:significant+ is +true+).
  280. # You can customize the format in the +options+ hash.
  281. #
  282. # ==== Options
  283. #
  284. # * <tt>:locale</tt> - Sets the locale to be used for formatting
  285. # (defaults to current locale).
  286. # * <tt>:precision</tt> - Sets the precision of the number
  287. # (defaults to 3).
  288. # * <tt>:significant</tt> - If +true+, precision will be the #
  289. # of significant_digits. If +false+, the # of fractional
  290. # digits (defaults to +false+).
  291. # * <tt>:separator</tt> - Sets the separator between the
  292. # fractional and integer digits (defaults to ".").
  293. # * <tt>:delimiter</tt> - Sets the thousands delimiter (defaults
  294. # to "").
  295. # * <tt>:strip_insignificant_zeros</tt> - If +true+ removes
  296. # insignificant zeros after the decimal separator (defaults to
  297. # +false+).
  298. #
  299. # ==== Examples
  300. #
  301. # number_to_rounded(111.2345) # => 111.235
  302. # number_to_rounded(111.2345, precision: 2) # => 111.23
  303. # number_to_rounded(13, precision: 5) # => 13.00000
  304. # number_to_rounded(389.32314, precision: 0) # => 389
  305. # number_to_rounded(111.2345, significant: true) # => 111
  306. # number_to_rounded(111.2345, precision: 1, significant: true) # => 100
  307. # number_to_rounded(13, precision: 5, significant: true) # => 13.000
  308. # number_to_rounded(111.234, locale: :fr) # => 111,234
  309. #
  310. # number_to_rounded(13, precision: 5, significant: true, strip_insignificant_zeros: true)
  311. # # => 13
  312. #
  313. # number_to_rounded(389.32314, precision: 4, significant: true) # => 389.3
  314. # number_to_rounded(1111.2345, precision: 2, separator: ',', delimiter: '.')
  315. # # => 1.111,23
  316. def number_to_rounded(number, options = {})
  317. return number unless valid_float?(number)
  318. number = Float(number)
  319. options = options.symbolize_keys
  320. defaults = format_options(options[:locale], :precision)
  321. options = defaults.merge!(options)
  322. precision = options.delete :precision
  323. significant = options.delete :significant
  324. strip_insignificant_zeros = options.delete :strip_insignificant_zeros
  325. if significant && precision > 0
  326. if number == 0
  327. digits, rounded_number = 1, 0
  328. else
  329. digits = (Math.log10(number.abs) + 1).floor
  330. rounded_number = (BigDecimal.new(number.to_s) / BigDecimal.new((10 ** (digits - precision)).to_f.to_s)).round.to_f * 10 ** (digits - precision)
  331. digits = (Math.log10(rounded_number.abs) + 1).floor # After rounding, the number of digits may have changed
  332. end
  333. precision -= digits
  334. precision = 0 if precision < 0 # don't let it be negative
  335. else
  336. rounded_number = BigDecimal.new(number.to_s).round(precision).to_f
  337. rounded_number = rounded_number.abs if rounded_number.zero? # prevent showing negative zeros
  338. end
  339. formatted_number = self.number_to_delimited("%01.#{precision}f" % rounded_number, options)
  340. if strip_insignificant_zeros
  341. escaped_separator = Regexp.escape(options[:separator])
  342. formatted_number.sub(/(#{escaped_separator})(\d*[1-9])?0+\z/, '\1\2').sub(/#{escaped_separator}\z/, '')
  343. else
  344. formatted_number
  345. end
  346. end
  347. # Formats the bytes in +number+ into a more understandable
  348. # representation (e.g., giving it 1500 yields 1.5 KB). This
  349. # method is useful for reporting file sizes to users. You can
  350. # customize the format in the +options+ hash.
  351. #
  352. # See <tt>number_to_human</tt> if you want to pretty-print a
  353. # generic number.
  354. #
  355. # ==== Options
  356. #
  357. # * <tt>:locale</tt> - Sets the locale to be used for formatting
  358. # (defaults to current locale).
  359. # * <tt>:precision</tt> - Sets the precision of the number
  360. # (defaults to 3).
  361. # * <tt>:significant</tt> - If +true+, precision will be the #
  362. # of significant_digits. If +false+, the # of fractional
  363. # digits (defaults to +true+)
  364. # * <tt>:separator</tt> - Sets the separator between the
  365. # fractional and integer digits (defaults to ".").
  366. # * <tt>:delimiter</tt> - Sets the thousands delimiter (defaults
  367. # to "").
  368. # * <tt>:strip_insignificant_zeros</tt> - If +true+ removes
  369. # insignificant zeros after the decimal separator (defaults to
  370. # +true+)
  371. # * <tt>:prefix</tt> - If +:si+ formats the number using the SI
  372. # prefix (defaults to :binary)
  373. #
  374. # ==== Examples
  375. #
  376. # number_to_human_size(123) # => 123 Bytes
  377. # number_to_human_size(1234) # => 1.21 KB
  378. # number_to_human_size(12345) # => 12.1 KB
  379. # number_to_human_size(1234567) # => 1.18 MB
  380. # number_to_human_size(1234567890) # => 1.15 GB
  381. # number_to_human_size(1234567890123) # => 1.12 TB
  382. # number_to_human_size(1234567, precision: 2) # => 1.2 MB
  383. # number_to_human_size(483989, precision: 2) # => 470 KB
  384. # number_to_human_size(1234567, precision: 2, separator: ',') # => 1,2 MB
  385. #
  386. # Non-significant zeros after the fractional separator are stripped out by
  387. # default (set <tt>:strip_insignificant_zeros</tt> to +false+ to change that):
  388. #
  389. # number_to_human_size(1234567890123, precision: 5) # => "1.1229 TB"
  390. # number_to_human_size(524288000, precision: 5) # => "500 MB"
  391. def number_to_human_size(number, options = {})
  392. options = options.symbolize_keys
  393. return number unless valid_float?(number)
  394. number = Float(number)
  395. defaults = format_options(options[:locale], :human)
  396. options = defaults.merge!(options)
  397. #for backwards compatibility with those that didn't add strip_insignificant_zeros to their locale files
  398. options[:strip_insignificant_zeros] = true if not options.key?(:strip_insignificant_zeros)
  399. storage_units_format = translate_number_value_with_default('human.storage_units.format', :locale => options[:locale], :raise => true)
  400. base = options[:prefix] == :si ? 1000 : 1024
  401. if number.to_i < base
  402. unit = translate_number_value_with_default('human.storage_units.units.byte', :locale => options[:locale], :count => number.to_i, :raise => true)
  403. storage_units_format.gsub(/%n/, number.to_i.to_s).gsub(/%u/, unit)
  404. else
  405. max_exp = STORAGE_UNITS.size - 1
  406. exponent = (Math.log(number) / Math.log(base)).to_i # Convert to base
  407. exponent = max_exp if exponent > max_exp # we need this to avoid overflow for the highest unit
  408. number /= base ** exponent
  409. unit_key = STORAGE_UNITS[exponent]
  410. unit = translate_number_value_with_default("human.storage_units.units.#{unit_key}", :locale => options[:locale], :count => number, :raise => true)
  411. formatted_number = self.number_to_rounded(number, options)
  412. storage_units_format.gsub(/%n/, formatted_number).gsub(/%u/, unit)
  413. end
  414. end
  415. # Pretty prints (formats and approximates) a number in a way it
  416. # is more readable by humans (eg.: 1200000000 becomes "1.2
  417. # Billion"). This is useful for numbers that can get very large
  418. # (and too hard to read).
  419. #
  420. # See <tt>number_to_human_size</tt> if you want to print a file
  421. # size.
  422. #
  423. # You can also define you own unit-quantifier names if you want
  424. # to use other decimal units (eg.: 1500 becomes "1.5
  425. # kilometers", 0.150 becomes "150 milliliters", etc). You may
  426. # define a wide range of unit quantifiers, even fractional ones
  427. # (centi, deci, mili, etc).
  428. #
  429. # ==== Options
  430. #
  431. # * <tt>:locale</tt> - Sets the locale to be used for formatting
  432. # (defaults to current locale).
  433. # * <tt>:precision</tt> - Sets the precision of the number
  434. # (defaults to 3).
  435. # * <tt>:significant</tt> - If +true+, precision will be the #
  436. # of significant_digits. If +false+, the # of fractional
  437. # digits (defaults to +true+)
  438. # * <tt>:separator</tt> - Sets the separator between the
  439. # fractional and integer digits (defaults to ".").
  440. # * <tt>:delimiter</tt> - Sets the thousands delimiter (defaults
  441. # to "").
  442. # * <tt>:strip_insignificant_zeros</tt> - If +true+ removes
  443. # insignificant zeros after the decimal separator (defaults to
  444. # +true+)
  445. # * <tt>:units</tt> - A Hash of unit quantifier names. Or a
  446. # string containing an i18n scope where to find this hash. It
  447. # might have the following keys:
  448. # * *integers*: <tt>:unit</tt>, <tt>:ten</tt>,
  449. # *<tt>:hundred</tt>, <tt>:thousand</tt>, <tt>:million</tt>,
  450. # *<tt>:billion</tt>, <tt>:trillion</tt>,
  451. # *<tt>:quadrillion</tt>
  452. # * *fractionals*: <tt>:deci</tt>, <tt>:centi</tt>,
  453. # *<tt>:mili</tt>, <tt>:micro</tt>, <tt>:nano</tt>,
  454. # *<tt>:pico</tt>, <tt>:femto</tt>
  455. # * <tt>:format</tt> - Sets the format of the output string
  456. # (defaults to "%n %u"). The field types are:
  457. # * %u - The quantifier (ex.: 'thousand')
  458. # * %n - The number
  459. #
  460. # ==== Examples
  461. #
  462. # number_to_human(123) # => "123"
  463. # number_to_human(1234) # => "1.23 Thousand"
  464. # number_to_human(12345) # => "12.3 Thousand"
  465. # number_to_human(1234567) # => "1.23 Million"
  466. # number_to_human(1234567890) # => "1.23 Billion"
  467. # number_to_human(1234567890123) # => "1.23 Trillion"
  468. # number_to_human(1234567890123456) # => "1.23 Quadrillion"
  469. # number_to_human(1234567890123456789) # => "1230 Quadrillion"
  470. # number_to_human(489939, precision: 2) # => "490 Thousand"
  471. # number_to_human(489939, precision: 4) # => "489.9 Thousand"
  472. # number_to_human(1234567, precision: 4,
  473. # significant: false) # => "1.2346 Million"
  474. # number_to_human(1234567, precision: 1,
  475. # separator: ',',
  476. # significant: false) # => "1,2 Million"
  477. #
  478. # Non-significant zeros after the decimal separator are stripped
  479. # out by default (set <tt>:strip_insignificant_zeros</tt> to
  480. # +false+ to change that):
  481. #
  482. # number_to_human(12345012345, significant_digits: 6) # => "12.345 Billion"
  483. # number_to_human(500000000, precision: 5) # => "500 Million"
  484. #
  485. # ==== Custom Unit Quantifiers
  486. #
  487. # You can also use your own custom unit quantifiers:
  488. # number_to_human(500000, units: { unit: 'ml', thousand: 'lt' }) # => "500 lt"
  489. #
  490. # If in your I18n locale you have:
  491. #
  492. # distance:
  493. # centi:
  494. # one: "centimeter"
  495. # other: "centimeters"
  496. # unit:
  497. # one: "meter"
  498. # other: "meters"
  499. # thousand:
  500. # one: "kilometer"
  501. # other: "kilometers"
  502. # billion: "gazillion-distance"
  503. #
  504. # Then you could do:
  505. #
  506. # number_to_human(543934, units: :distance) # => "544 kilometers"
  507. # number_to_human(54393498, units: :distance) # => "54400 kilometers"
  508. # number_to_human(54393498000, units: :distance) # => "54.4 gazillion-distance"
  509. # number_to_human(343, units: :distance, precision: 1) # => "300 meters"
  510. # number_to_human(1, units: :distance) # => "1 meter"
  511. # number_to_human(0.34, units: :distance) # => "34 centimeters"
  512. def number_to_human(number, options = {})
  513. options = options.symbolize_keys
  514. return number unless valid_float?(number)
  515. number = Float(number)
  516. defaults = format_options(options[:locale], :human)
  517. options = defaults.merge!(options)
  518. #for backwards compatibility with those that didn't add strip_insignificant_zeros to their locale files
  519. options[:strip_insignificant_zeros] = true if not options.key?(:strip_insignificant_zeros)
  520. inverted_du = DECIMAL_UNITS.invert
  521. units = options.delete :units
  522. unit_exponents = case units
  523. when Hash
  524. units
  525. when String, Symbol
  526. I18n.translate(:"#{units}", :locale => options[:locale], :raise => true)
  527. when nil
  528. translate_number_value_with_default("human.decimal_units.units", :locale => options[:locale], :raise => true)
  529. else
  530. raise ArgumentError, ":units must be a Hash or String translation scope."
  531. end.keys.map{|e_name| inverted_du[e_name] }.sort_by{|e| -e}
  532. number_exponent = number != 0 ? Math.log10(number.abs).floor : 0
  533. display_exponent = unit_exponents.find{ |e| number_exponent >= e } || 0
  534. number /= 10 ** display_exponent
  535. unit = case units
  536. when Hash
  537. units[DECIMAL_UNITS[display_exponent]]
  538. when String, Symbol
  539. I18n.translate(:"#{units}.#{DECIMAL_UNITS[display_exponent]}", :locale => options[:locale], :count => number.to_i)
  540. else
  541. translate_number_value_with_default("human.decimal_units.units.#{DECIMAL_UNITS[display_exponent]}", :locale => options[:locale], :count => number.to_i)
  542. end
  543. decimal_format = options[:format] || translate_number_value_with_default('human.decimal_units.format', :locale => options[:locale])
  544. formatted_number = self.number_to_rounded(number, options)
  545. decimal_format.gsub(/%n/, formatted_number).gsub(/%u/, unit).strip
  546. end
  547. def self.private_module_and_instance_method(method_name) #:nodoc:
  548. private method_name
  549. private_class_method method_name
  550. end
  551. private_class_method :private_module_and_instance_method
  552. def format_options(locale, namespace = nil) #:nodoc:
  553. default_format_options(namespace).merge!(i18n_format_options(locale, namespace))
  554. end
  555. private_module_and_instance_method :format_options
  556. def default_format_options(namespace = nil) #:nodoc:
  557. options = DEFAULTS[:format].dup
  558. options.merge!(DEFAULTS[namespace][:format]) if namespace
  559. options
  560. end
  561. private_module_and_instance_method :default_format_options
  562. def i18n_format_options(locale, namespace = nil) #:nodoc:
  563. options = I18n.translate(:'number.format', locale: locale, default: {}).dup
  564. if namespace
  565. options.merge!(I18n.translate(:"number.#{namespace}.format", locale: locale, default: {}))
  566. end
  567. options
  568. end
  569. private_module_and_instance_method :i18n_format_options
  570. def translate_number_value_with_default(key, i18n_options = {}) #:nodoc:
  571. default = key.split('.').reduce(DEFAULTS) { |defaults, k| defaults[k.to_sym] }
  572. I18n.translate(key, { default: default, scope: :number }.merge!(i18n_options))
  573. end
  574. private_module_and_instance_method :translate_number_value_with_default
  575. def valid_float?(number) #:nodoc:
  576. Float(number)
  577. rescue ArgumentError, TypeError
  578. false
  579. end
  580. private_module_and_instance_method :valid_float?
  581. end
  582. end