Skip to content

Instantly share code, notes, and snippets.

@figloalds
Last active March 24, 2021 16:30
Show Gist options
  • Save figloalds/c4d5903d0efa4d34c37a258453097629 to your computer and use it in GitHub Desktop.
Save figloalds/c4d5903d0efa4d34c37a258453097629 to your computer and use it in GitHub Desktop.
let uni = [
'',
'um', 'dois', 'três', 'quatro', 'cinco', 'seis', 'sete', 'oito', 'nove',
'dez',
'onze', 'doze', 'treze', 'quatorze', 'quinze', 'dezesseis', 'dezessete', 'dezoito', 'dezenove',
]
let dezenas = [
'',
'dez',
'vinte',
'trinta',
'quarenta',
'cinquenta',
'sessenta',
'setenta',
'oitenta',
'noventa',
]
let centenas = [
'',
'cento',
'duzentos',
'trezentos',
'quatrocentos',
'quinhentos',
'seicentos',
'setecentos',
'oitocentos',
'novecentos',
]
let grandezas = [
'',
'mil',
'milh',
'bilh',
'trilh',
'quatrilh',
'quintilh',
];
let gSing = 'ão';
let gPlu = 'ões'
let g = 0;
let popUnit = strRepr => {
if(strRepr.length > 3) {
let idx = strRepr.length - 3;
return [
strRepr.substr(0, idx),
strRepr.substr(idx, 3)
]
} else {
return ['', strRepr];
}
}
const subNumPorExtenso = strNum => {
while(strNum.length < 3) {
strNum = '0' + strNum;
}
let centena = Number(strNum.substr(0, 1));
let dezena = Number(strNum.substr(1));
let retv = '';
retv += centenas[centena];
if(centena === 1 && dezena === 0) {
return 'cem';
}
if(centena > 0) {
retv += ' e '
}
if(dezena < 20) {
retv += uni[dezena];
} else {
retv += dezenas[Math.floor(dezena / 10)];
unidade = dezena % 10;
if(unidade > 0) {
retv += ' e ' + uni[unidade];
}
}
return retv;
};
const numPorExtenso = (n) => {
let strRepr = String(n);
let grupos = [];
while(strRepr) {
let [a, b] = popUnit(strRepr);
grupos.push(b);
strRepr = a;
}
let retv = '';
let ultima = grupos.findIndex(x=> Number(x) > 0);
let penultima = ultima + grupos.slice(ultima + 1).findIndex(x=> Number(x) > 0) + 1;
let vlrUni = Number(grupos[ultima]);
for(let i = grupos.length - 1; i >= 0; i--) {
let tamGrandeza = Number(grupos[i]);
if(tamGrandeza > 0) {
if(i === 1 && tamGrandeza === 1) {
retv += ''
} else {
retv += subNumPorExtenso(grupos[i]) + ' ';
}
if(i > 0) {
let q = i > 1 ? tamGrandeza > 1 ? gPlu : gSing : '';
retv += grandezas[i] + q;
if(i === penultima && i !== ultima && (vlrUni < 20 && vlrUni > 0)) {
retv += ' e '
} else {
if(i > ultima) {
retv += ', ';
}
}
}
}
}
return retv;
}
console.log(numPorExtenso(1997))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment