Currency formatting

Asked

Viewed 80 times

1

I have the following script in my HTML, what it does is simply check a checkbox if it is selected or not and in case it is adding a value, my question is, how to make this value be formatted in currency? For example when instead of appearing 400,00 or 1,455,80 it appears all together as an integer in case 400 and 145580, how to 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();

  • 1

    price.toFixed(2) That’s what you wanted?

  • I don’t know, I started working with js now, I’m going to do some research on it, thanks.

  • 1

    What is the reason for this value with comma in the add script += 400,00; Because it does not enter value that javascript requires for calculations, ie 400.00 with decimal point?

  • This value will be displayed to the user, the idea is that when he marks a checkbox add a value to a visible field, so that some checkboxs add 400,00 and other 1.455,80, would like the user can view the common real formatting and not that appeared "1455.8" or "400".

  • 1

    can you post html? this script is not complete, it is difficult to reproduce an example that we can test

  • It is not necessary, I am taking a look at another similar question I believe that the answers from there can help me, since my question has been duplicated. If I don’t get anything open another question specifying my problem better, but thanks for the help.

  • see if my answer helps

  • 1

    the question should not be changed because the answer becomes half meaningless

Show 3 more comments

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 have the American default for integers and decimals, that is, you will not be able to do the calculation correctly, if there are decimal values, if you do not exchange the comma for the dot.

  • It worked for the 400.00 has to do something similar to 1.455,80? the way it is now the number is expressed "145.580,00".

  • It worked, all right thank you very much.

Browser other questions tagged

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