Convert to the nomenclature of R $ [duplicate]

1

Colleagues.

I'm getting the value of a product in javascript as follows:

totalGeralSomar.toFixed(2)

But it returns me like this: 1400.00. Would you have any means of returning 1,400.00?

    
asked by anonymous 25.09.2015 / 02:01

2 answers

3

Dude 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 use it like this:

(1400).formatMoney(2, ',', '.');
your_number '), formatMoney ( decimal ,' separator2 ',' p>

The result will be:

1.400,00
    
25.09.2015 / 02:46
1

Using javaScript pure, you can use the Replace ( ) to do what you want. Below I will leave two functions, one to format the formatted value, and another to remove the formatting and return the value as an integer, if you need to use it 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

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

    
25.09.2015 / 02:43