Convert to R$nomenclature

Asked

Viewed 314 times

1

Colleagues.

I’m taking the value of a javascript product as follows:

totalGeralSomar.toFixed(2)

Only that it returns me as follows: 1400.00. It would have some way to return 1.400,00?

2 answers

3


Cara uses this function in javascript:

Number.prototype.formatMoney = function(c, d, t){
var n = this, 
    c = isNaN(c = Math.abs(c)) ? 2 : c, 
    d = d == undefined ? "." : d, 
    t = t == undefined ? "," : t, 
    s = n < 0 ? "-" : "", 
    i = parseInt(n = Math.abs(+n || 0).toFixed(c)) + "", 
    j = (j = i.length) > 3 ? j % 3 : 0;
   return s + (j ? i.substr(0, j) + t : "") + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + t) + (c ? d + Math.abs(n - i).toFixed(c).slice(2) : "");
 };

And uses like this:

(1400).formatMoney(2, ',', '.');

(teu_numero).formatMoney(decimal, 'separator 2', 'separator 1');

The result will be:

1.400,00

1

Using javaScript pure, you can use the method Replace() to do what you wish. Below I will leave two functions, one to format the formatted value, and another to remove the formatting and return the value as integer, if you need to use the same in javascript.

<script type="text/javascript">
 
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 'R$' + tmp;
}
 
 
var int = getMoney( test );
//alert( int );
 
 
console.log( formatReal( 1000 ) );
console.log( formatReal( 19990020 ) );
console.log( formatReal( 12006 ) );
console.log( formatReal( 111090 ) );
console.log( formatReal( 1111 ) );
console.log( formatReal( 120090 ) );
console.log( formatReal( int ) );
 
 
</script>

Source: Format Currency

Obs.: To see the result, just run the code with the console from your open browser (F12).

Browser other questions tagged

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