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