Format pennies in real

Asked

Viewed 668 times

-7

Good afternoon, you guys. I’m trying to format pennies for real. That is to say

var number = 312311

turn:

R$3.123,11

But I’m having a hard time. How would I do that?

  • 2

    And how do you know it’s not $312,311? or $312,311.00?

  • That value 312311 sane trezentos e doze mil e trezentos e onze pennies?

2 answers

1

JS already has by default a function for currency formatting is the toLocaleString()

An example of her use in your case.

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

However it is worth noting that the var number = 312311 may not be R$3.123,11 at all times.

  • Problem with that is that he adds ,00 at the end and doesn’t understand that my last two digits are already pennies

  • 3

    The way you bring the numbers no function will understand, because she can be so much R$ 312,311 as R$3.123,11 or even as R$ 312.311,00 which is the return of toLocaleString()

  • 3

    You need to treat this number before using toLocaleString.

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>

Browser other questions tagged

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