Javascript formatting value BRL

Asked

Viewed 55 times

0

I’m having a hard time formatting a BRL value for a form. I would like when the user enters the value in BRL the point and comma are positioned automatically. Without the need of the user to type them. Please, would anyone have an idea or a script ready? thank you very much

1 answer

0

I found a solution with Reg Exp. You use the regular expression to locate the numbers values and replace them with 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 locates the "value" in this excerpt.

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

and replaces the value in the format of "Brazilian real"

tmp.replace(/([0-9]{3}),([0-9]{2}$)/g, ".$1,$2");
  • Thanks for the feedback. Just one question. I’m using a form for html. How I call the script to validate?

  • could you put in the html code? then I’ll tell you how you could put it.

Browser other questions tagged

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