Currency formatting [duplicate]

1

I have the following script in my HTML, what it does is simply check a checkbox whether or not it is selected and in case it is adding a value, my question is, how do I make this value to be formatted in currency? For example, instead of appearing 400.00 or 1455.80 it all appears together as an integer in case 400 and 145580, how do you show the values in real?

Script:

function check() {
  var basic = 0;
  var add = 0;  

 
  if(document.getElementById("cl45").checked) {
    add += 145580;  
  }
  if(document.getElementById("trigger").checked) {
    add += 40000;
  }
  var p = basic + add;
    
   
  var price ="R$ " + p; 
  document.getElementById('total2').innerHTML = price;  
 }

check();
    
asked by anonymous 04.09.2017 / 13:15

1 answer

2

function check() {
      var basic = 0;
      var add = 0;  

      add += 1455.80;
      
      var p = (basic + add).toFixed(2);
      
      var result = p.toString();
      
    	//substitui separador decimal ponto por virgula
    	result=result.replace(".", ",");
    	//a regex abaixo coloca um ponto a esquerda de cada grupo de 3 digitos desde que não seja no inicio do numero
    	result = result.replace(/\B(?=(\d{3})+(?!\d))/g, ".");
    	
    	var price ="R$ " + result;
    	
    	document.getElementById('total2').innerHTML = price; 

}
<input type="checkbox" id="trigger" onclick="check()">

<span id="total2"></span>
  

All languages default to integer and decimal, meaning you can not do the calculation correctly, if there are decimal values, if you do not change the decimal point.

    
04.09.2017 / 15:44