Skip to content

Instantly share code, notes, and snippets.

@juanplopes
Created January 25, 2013 17:47
Show Gist options
  • Save juanplopes/4636434 to your computer and use it in GitHub Desktop.
Save juanplopes/4636434 to your computer and use it in GitHub Desktop.
# encoding: utf-8
N = [
[nil, 'um', 'dois', 'três', 'quatro', 'cinco', 'seis', 'sete', 'oito', 'nove'],
[nil, 'dez', 'vinte', 'trinta', 'quarenta', 'cinquenta', 'sessenta', 'setenta', 'oitenta', 'noventa'],
[nil, 'cento', 'duzentos', 'trezentos', 'quatrocentos', 'quinhentos', 'seiscentos', 'setecentos', 'oitocentos', 'novecentos'],
]
T = [nil, 'onze', 'doze', 'treze', 'quatorze', 'quinze', 'dezesseis', 'dezessete', 'dezoito', 'dezenove']
O = [['',''], [' mil', ' mil'], [' milhão', ' milhões'], [' bilhão', ' bilhões']]
def extenso(numero)
return [
nomeado(numero, 'real', 'reais'),
nomeado(numero*100%100, 'centavo', 'centavos')
].compact.join(' e ')
end
def nomeado(n, singular, plural)
return nil if n.to_i == 0
return maior(n.to_i) + ' ' + (n.to_i==1?singular:plural)
end
def maior(n, ordem=0)
return [
n/1000>0 ? maior(n/1000, ordem+1) : nil,
n%1000>0 ? menor_ordem(n%1000, ordem) : nil
].compact.join(n%100 == 0 || n%1000/100 == 0 || n%1000000/1000 == 0 ? ' e ': ', ')
end
def menor_ordem(n, ordem)
return nil if n == 0
return 'mil' if n == 1 and ordem == 1
return menor(n).compact.join(' e ') + O[ordem][n == 1 ? 0 : 1]
end
def menor(n, ordem=0)
return [] if n == 0
return ['cem'] if n == 100
return menor(n/100, ordem+2) + [T[n%100-10]] if (11..19) === (n%100) and ordem == 0
return menor(n/10, ordem+1) + [N[ordem][n%10]]
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment