How to transform numeric digits into numbers in full?

Asked

Viewed 15,929 times

41

I’d like to know how to turn numerical digits in spelled numbers, as shown in the example below:

0          -> retorna "zero"
5          -> retorna "cinco"
2014       -> retorna "dois mil e quatorze"
1034       -> retorna "mil e trinta e quatro"
2566       -> retorna "dois mil quinhentos e sessenta e seis"
78391      -> retorna "setenta e oito mil trezentos e noventa e um"
999999     -> retorna "novecentos e noventa e nove mil novecentos e noventa e nove"
1000000000 -> retorna "um bilhão"
  • 7

    I believe that Javascript does not have a function to do this directly. You have tried searching for some ready-made code, for example: http://jsfromhell.com/pt/string/extenso

  • 3

    @Luizvieira Turn this into an answer

  • Oops, I have a full library to write numbers in full call Extenso.js. This library... - Accepts numbers up to two decimals. - Accepts negative numbers. - Accepts decimal numbers. - Accepts configuration of different dialects. - Accepts gender configuration (male/female). - Accepts monetary values (Reais, Euros, and is suitable for +). *** You can take a look at it and who knows how to help improve the project . Official website: https://extenso.js.org.

2 answers

32


Javascript does not have a native function to perform this process.

However, you can use this function to return an extended number:

//+ Carlos R. L. Rodrigues
//@ http://jsfromhell.com/string/extenso [rev. #3]
String.prototype.extenso = function(c){
    var ex = [
        ["zero", "um", "dois", "três", "quatro", "cinco", "seis", "sete", "oito", "nove", "dez", "onze", "doze", "treze", "quatorze", "quinze", "dezesseis", "dezessete", "dezoito", "dezenove"],
        ["dez", "vinte", "trinta", "quarenta", "cinqüenta", "sessenta", "setenta", "oitenta", "noventa"],
        ["cem", "cento", "duzentos", "trezentos", "quatrocentos", "quinhentos", "seiscentos", "setecentos", "oitocentos", "novecentos"],
        ["mil", "milhão", "bilhão", "trilhão", "quadrilhão", "quintilhão", "sextilhão", "setilhão", "octilhão", "nonilhão", "decilhão", "undecilhão", "dodecilhão", "tredecilhão", "quatrodecilhão", "quindecilhão", "sedecilhão", "septendecilhão", "octencilhão", "nonencilhão"]
    ];
    var a, n, v, i, n = this.replace(c ? /[^,\d]/g : /\D/g, "").split(","), e = " e ", $ = "real", d = "centavo", sl;
    for(var f = n.length - 1, l, j = -1, r = [], s = [], t = ""; ++j <= f; s = []){
        j && (n[j] = (("." + n[j]) * 1).toFixed(2).slice(2));
        if(!(a = (v = n[j]).slice((l = v.length) % 3).match(/\d{3}/g), v = l % 3 ? [v.slice(0, l % 3)] : [], v = a ? v.concat(a) : v).length) continue;
        for(a = -1, l = v.length; ++a < l; t = ""){
            if(!(i = v[a] * 1)) continue;
            i % 100 < 20 && (t += ex[0][i % 100]) ||
            i % 100 + 1 && (t += ex[1][(i % 100 / 10 >> 0) - 1] + (i % 10 ? e + ex[0][i % 10] : ""));
            s.push((i < 100 ? t : !(i % 100) ? ex[2][i == 100 ? 0 : i / 100 >> 0] : (ex[2][i / 100 >> 0] + e + t)) +
            ((t = l - a - 2) > -1 ? " " + (i > 1 && t > 0 ? ex[3][t].replace("ão", "ões") : ex[3][t]) : ""));
        }
        a = ((sl = s.length) > 1 ? (a = s.pop(), s.join(" ") + e + a) : s.join("") || ((!j && (n[j + 1] * 1 > 0) || r.length) ? "" : ex[0][0]));
        a && r.push(a + (c ? (" " + (v.join("") * 1 > 1 ? j ? d + "s" : (/0{6,}$/.test(n[0]) ? "de " : "") + $.replace("l", "is") : j ? d : $)) : ""));
    }
    return r.join(e);
}

She uses String.prototype so adds a method applied to all strings. For example:

"123".extenso();

How to use it you can see here

Reference:

Jsfromhell

  • 5

    From what I see in the code, you don’t need to include the prototype library (is that what you meant?). But I have to say, I had contact with this guy’s codes several years ago. At first I was impressed, then I started to hate. I don’t like intentionally obscure codes.

  • 1

    @bfavaretto This is not the prototype library (at first I also got this impression). The original code seems to use String.extenso instead of String.prototype.extenso - which, if it ever worked, doesn’t work today.

  • @bfavaretto that’s what I meant, I’m wrong?

  • I don’t understand why the function is "123".extenso() and not 123.extenso(). That had to extend Number and not String to work that way.

  • The function does not depend on the prototype library. It just adds a method to all strings to be defined in String.prototype. That’s what confused you, @Pauloroberto?

  • 1

    @mgibsonbr The code that is to download on the site is correct, the documentation is what is strange - like the code itself, by the way :P

  • @Gustavorodrigues You are right, but it seems simple to adapt: http://jsfiddle.net/VyMkP/

  • 1

    The code seems hard to understand, but only the variables that are compressed. It is simple to change that, the use of function that is not very intuitive.

  • yes @bfavaretto I thought it was the prototype prototype

  • Isn’t there any NPM module or project on Github (or similar) for that? The function is not well documented, is overshadowed and does not yet work with decimals: (12.34).extenso() => um mil e duzentos e trinta e quatro

  • @Gustavorodrigues If you have not know, I looked for what I found was just this :p I also found such a NumberInWords() which is here http://snipplr.com/view/65870/

  • 3

    I found a module: https://github.com/jmosbech/spell-it. It is not in English but it is easy to edit. There are options to correct any problems, including decimals.

  • Que dahora @Gustavorodrigues !

Show 8 more comments

-2

function Extenso(vlr){

    var Num=parseFloat(vlr);
    if (vlr == 0)
    {
    document.getElementById('teste').value = "zero";
}else{

    var inteiro = parseInt(vlr);; // parte inteira do valor
    if(inteiro<1000000000000000)
    {

    var resto = Num.toFixed(2) - inteiro.toFixed(2);       // parte fracionária do valor
    resto=resto.toFixed(2)
    var vlrS =  inteiro.toString();    

    var cont=vlrS.length;
    var extenso="";
    var auxnumero;
    var auxnumero2;
    var auxnumero3;

    var unidade =["", "um", "dois", "três", "quatro", "cinco",
    "seis", "sete", "oito", "nove", "dez", "onze",
    "doze", "treze", "quatorze", "quinze", "dezesseis",
    "dezessete", "dezoito", "dezenove"];

var centena = ["", "cento", "duzentos", "trezentos",
    "quatrocentos", "quinhentos", "seiscentos",
    "setecentos", "oitocentos", "novecentos"];

var dezena = ["", "", "vinte", "trinta", "quarenta", "cinquenta",
    "sessenta", "setenta", "oitenta", "noventa"];

var qualificaS = ["reais", "mil", "milhão", "bilhão", "trilhão"];
var qualificaP = ["reais", "mil", "milhões", "bilhões", "trilhões"];

for (var i=cont;i > 0;i--)
{   
    var verifica1="";
    var verifica2=0;
    var verifica3=0;
    auxnumero2="";
    auxnumero3="";
    auxnumero=0;
    auxnumero2 = vlrS.substr(cont-i,1);    
    auxnumero = parseInt(auxnumero2);


    if((i==14)||(i==11)||(i==8)||(i==5)||(i==2))
    {
        auxnumero2 = vlrS.substr(cont-i,2);
        auxnumero = parseInt(auxnumero2);
    }

    if((i==15)||(i==12)||(i==9)||(i==6)||(i==3))
    {   
        extenso=extenso+centena[auxnumero];
        auxnumero2 = vlrS.substr(cont-i+1,1)
        auxnumero3 = vlrS.substr(cont-i+2,1)

        if((auxnumero2!="0")||(auxnumero3!="0"))
        extenso+=" e ";

    }else

    if(auxnumero>19){
        auxnumero2 = vlrS.substr(cont-i,1);
        auxnumero = parseInt(auxnumero2);
        extenso=extenso+dezena[auxnumero];
        auxnumero3 = vlrS.substr(cont-i+1,1)

        if((auxnumero3!="0")&&(auxnumero2!="1"))
        extenso+=" e ";
    }
        else if((auxnumero<=19)&&(auxnumero>9)&&((i==14)||(i==11)||(i==8)||(i==5)||(i==2)))
        {
            extenso=extenso+unidade[auxnumero];   
        }else if((auxnumero<10)&&((i==13)||(i==10)||(i==7)||(i==4)||(i==1)))
        {
            auxnumero3 = vlrS.substr(cont-i-1,1);
            if((auxnumero3!="1")&&(auxnumero3!=""))
            extenso=extenso+unidade[auxnumero]; 
        }

        if(i%3==1)
        {       
            verifica3 = cont-i;
            if(verifica3==0)
            verifica1 = vlrS.substr(cont-i,1);

            if(verifica3==1)
            verifica1 = vlrS.substr(cont-i-1,2);

            if(verifica3>1)
            verifica1 = vlrS.substr(cont-i-2,3);

         verifica2 = parseInt(verifica1);

         if(i==13)
         {
            if(verifica2==1){
            extenso=extenso+" "+qualificaS[4]+" ";
        }else if(verifica2!=0){extenso=extenso+" "+qualificaP[4]+" ";}}
            if(i==10)
            {
                if(verifica2==1){
                extenso=extenso+" "+qualificaS[3]+" ";
            }else if(verifica2!=0){extenso=extenso+" "+qualificaP[3]+" ";}}
            if(i==7)
            {
                if(verifica2==1){
                extenso=extenso+" "+qualificaS[2]+" ";
            }else if(verifica2!=0){extenso=extenso+" "+qualificaP[2]+" ";}}
            if(i==4)
            {
                if(verifica2==1){
                extenso=extenso+" "+qualificaS[1]+" ";
            }else if(verifica2!=0){extenso=extenso+" "+qualificaP[1]+" ";}}
            if(i==1)
            {
                if(verifica2==1){
                extenso=extenso+" "+qualificaS[0]+" ";
            }else {extenso=extenso+" "+qualificaP[0]+" ";}}
        }
    }
    resto = resto * 100;
    var aexCent=0;
    if(resto<=19&&resto>0)
    extenso+=" e "+unidade[resto]+" Centavos";
    if(resto>19)
    {
        aexCent=parseInt(resto/10);

    extenso+=" e "+dezena[aexCent]
    resto=resto-(aexCent*10);

    if(resto!=0)
    extenso+=" e "+unidade[resto]+" Centavos";
    else extenso+=" Centavos";
    }

    document.getElementById('teste').value = extenso;
}
else
{document.getElementById('teste').value = "Numero maior que 999 trilhões";}
}
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.