Format cents in real

-7

Good afternoon, guys. I'm trying to format cents in real. In other words,

var number = 312311

turn around:

R$3.123,11

But I'm having difficulties. How would you do that?

    
asked by anonymous 14.12.2018 / 19:41

2 answers

1

JS already has a function for formatting currencies by default toLocaleString ()

An example of using it in your case.

number.toLocaleString("pt-BR", {style: 'currency', currency: 'BRL' });

However, it should be noted that var number = 312311 may not be R$3.123,11 always.

    
14.12.2018 / 19:45
0

 
      var number = 312311;
      
      var emDecimal = (number/100);
      
      var strString = emDecimal.toString();
      
    	//substitui separador decimal ponto por virgula
    	strString=strString.replace(".", ",");
    	//a regex abaixo coloca um ponto a esquerda de cada grupo de 3 dígitos desde que não seja no inicio do numero
    	formatado = strString.replace(/\B(?=(\d{3})+(?!\d))/g, ".");
    	
    	var resultado ="R$ " + formatado;
    	
    	document.getElementById('real').innerHTML = resultado; 
<span id="real"></span>
    
15.12.2018 / 03:09