Format Brazilian currency in JavaScript

13

I have the following variable:

var atual = 600000.00 ;

Here we have the value six hundred thousand in the American standard, I would like it when I printed it on the screen like this:

600.000,00

I'm using jquery in the project if it helps.

    
asked by anonymous 03.02.2017 / 15:11

4 answers

10

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

<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 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>

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");

Font

    
03.02.2017 / 15:23
21

Solution with toLocaleString() .

var atual = 600000.00;

//com R$
var f = atual.toLocaleString('pt-br',{style: 'currency', currency: 'BRL'});

//sem R$
var f2 = atual.toLocaleString('pt-br', {minimumFractionDigits: 2});

console.log(f);
console.log(f2);
    
26.02.2017 / 17:26
0
function number_format(string,decimals=2,decimal=',',thousands='.',pre='R$ ',pos=' $'){
  var numbers = string.toString().match(/\d+/g).join([]);
  numbers = numbers.padStart(decimals+1, "0");
  var splitNumbers = numbers.split("").reverse();
  var mask = '';
  splitNumbers.forEach(function(d,i){
    if (i == decimals) { mask = decimal + mask; }
    if (i>(decimals+1) && ((i-2)%(decimals+1))==0) { mask = thousands + mask; }
    mask = d + mask;
  });
  return pre + mask + pos;
}
    
21.04.2018 / 00:54
0

Here's another solution.

function formatMoney(n, c, d, t) {
  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) : "");
}
console.log(formatMoney(600000.00));
console.log(formatMoney(10));
console.log(formatMoney(100));
console.log(formatMoney(0.5));
console.log(formatMoney(1500));
console.log(formatMoney(89));
    
09.11.2018 / 14:04