Show a number in 2 decimal places

5

How do I calculate a input (integer value) and a (real) currency variable in javascript ?

The result is 6.7 and not 6.70 (I have tried many examples here in the forum, but nothing yet).

function Calcular() {
  var valor1 = 3.35;
  var teste = Number(document.getElementById("teste").value);
  var result = document.getElementById("Resultado");
  if (result.textContent === undefined) {
    result.textContent = String(teste * valor1);
  } else { // IE
    result.innerText = String(teste * valor1);
  }
}
<input type="text" id="teste" name="teste" onkeyup="Calcular();" value="2">
<div id="Resultado"></div>
    
asked by anonymous 08.12.2017 / 12:27

3 answers

6

The Calculus you already do, so I understand what you want is to show the value in 2 decimal places, for this, you can use the #

  

The toFixed () method formats a number using fixed-point notation.

function Calcular() {
  var valor1 = 3.35;
  var teste = Number( document.getElementById( "teste" ).value);
  var result = document.getElementById( "Resultado" );
  if ( result.textContent === undefined ) {
    result.textContent =  (teste * valor1).toFixed(2);
  } else { // IE
    result.innerText =  (teste * valor1).toFixed(2);
  }
}
<input type="text" id="teste" name="teste" onkeyup="Calcular();" value="2" />

<div id="Resultado"></div>
    
08.12.2017 / 12:38
3

Javascript has a toFixed () method where you can determine how many decimal places you want to display your value

    
08.12.2017 / 12:35
3

You should tell JavasSript what is the precision of the Number variable you want, using toFixed .

  

NOTE: toFixed will transform your number into string .

Then it would look like this:

function Calcular() {
  var valor1 = 3.35;
  var teste = Number( document.getElementById( "teste" ).value);
  var result = document.getElementById( "Resultado" );
  
  /* Informando a precisão de 2 casas  */
  var valorFinal = (teste * valor1).toFixed(2);
  
  if ( result.textContent === undefined ) {
    result.textContent =  String( valorFinal );
  } else { // IE
    result.innerText =  String( valorFinal );
  }
}
<input type="text" id="teste" name="teste" onkeyup="Calcular();" value="2">
<div id="Resultado"></div>
    
08.12.2017 / 12:38