-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?
-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?
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
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()
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 javascript
You are not signed in. Login or sign up in order to post.
And how do you know it’s not $312,311? or $312,311.00?
– Woss
That value
312311
sanetrezentos e doze mil e trezentos e onze
pennies?– Sam