Formatting default value BRL in javascript

0

I'm having a hard time formatting a BRL value for a form. I would like that when the user enters the value in BRL the semicolon is positioned automatically. No need for the user to type them. Please, would anyone have an idea or a script ready? Many thanks.

    
asked by anonymous 08.01.2018 / 16:16

1 answer

0

I found a solution with Reg Exp. You use the regular expression to find the numbers values and replace them with the Real formatting.

var test = 'R$ 1.700,90';



function getMoney( str )
{

        return parseInt( str.replace(/[\D]+/g,'') );

}

function formatReal( int )

{

        var tmp = int+'';

        tmp = tmp.replace(/([0-9]{2})$/g, ",$1");

        if( tmp.length > 6 )

                tmp = tmp.replace(/([0-9]{3}),([0-9]{2}$)/g, ".$1,$2");


        return tmp;
}


var int = getMoney( test );

console.log( formatReal(1000) );

console.log( formatReal(12006) );

console.log( formatReal(1111) );

console.log( formatReal(120090) );

console.log( formatReal(int) );

Notice that it finds the "value" in this section.

tmp.replace(/([0-9]{2})$/g, ",$1");

and makes the substitution by the value in "Brazilian real" format

tmp.replace(/([0-9]{3}),([0-9]{2}$)/g, ".$1,$2");
    
08.01.2018 / 16:26