Show a number in 2 decimal places

Asked

Viewed 11,852 times

5

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

The result is being 6.7 and not 6.70 (I have tried many examples here of 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>

3 answers

7

The calculation you already do, so I understood what you want is to show the value in 2 decimal places, for this, you can use the method toFixed() of JS.

The toFixed() method formats a number using a 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>

4

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

4

You must inform the JavasSript what is the accuracy of the variable Number you want, using the toFixed.

OBS: toFixed will turn your number into a 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>

Browser other questions tagged

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