Module: BrazilianUtils::NumberUtils

Defined in:
lib/brazilian-utils/number-utils.rb

Overview

Utilities for writing numbers in Brazilian Portuguese cardinal words ("por extenso"), e.g. 1235 becomes "mil duzentos e trinta e cinco".

Constant Summary collapse

MAX_ABS_VALUE =
999_999_999_999_999
FEMININE_GENDERS =
%i[feminine feminino f].freeze

Class Method Summary collapse

Class Method Details

.convert_to_words(value, options = {}) ⇒ String

Writes an integer in Brazilian Portuguese cardinal words.

Examples:

convert_to_words(1235)     #=> "mil duzentos e trinta e cinco"
convert_to_words(100)      #=> "cem"
convert_to_words(-3)       #=> "menos três"
convert_to_words(2, gender: :feminine) #=> "duas"

Parameters:

  • value (Numeric) —

    The number to convert. Accepts integers from -999,999,999,999,999 to 999,999,999,999,999; a non-integer is truncated toward zero.

  • options (Hash) (defaults to: {}) —

    :gender (:masculine, default, or :feminine) agrees "um/uma", "dois/duas" and the hundreds.

Returns:

  • (String) —

    The textual representation, or an empty string for a value outside the supported range or not finite.



26
27
28
29
30
31
32
33
34
35
36
37
# File 'lib/brazilian-utils/number-utils.rb', line 26

def self.convert_to_words(value, options = {})
  return '' unless value.is_a?(Numeric)
  return '' if value.respond_to?(:finite?) && !value.finite?

  int_value = value.to_i
  return '' if int_value.abs > MAX_ABS_VALUE

  gender = (options[:gender] || options['gender'] || :masculine).to_sym
  negative = int_value.negative?
  words = number_to_words(int_value.abs, gender)
  negative ? "menos #{words}" : words
end