How to format number in 2 decimal places

Asked

Viewed 42 times

0

<script>
  function calcular() {
   var p = parseFloat(document.getElementById('peso').value);
   var e = parseFloat(document.getElementById('estatura').value);
   document.getElementById('imc').value = p / ((e * e) / 10000);                                
  }
</script>

<input type="text" class="form-control" id="imc" name="imc" onblur="calcular()"> 

1 answer

1

Using the function toFixed in its calculation.

function calcular() {
    var p = parseFloat(document.getElementById('peso').value);
    var e = parseFloat(document.getElementById('estatura').value);
    document.getElementById('imc').value = (p / ((e * e) / 10000)).toFixed(2) //duas casas decimais;
}
  • Thanks for the return Laércio, but it is not working, the number keeps appearing with several decimal places after the point.

  • worked when removing the dot and comma ";" . Any tips for learning javascript on the internet?

  • There are many courses at Udemy at affordable prices with good recommendations and many students, this one is free: https://www.youtube.com/playlist?list=PLHz_AreHm4dlsK3Nr9GVvXCbpQyHQl1o1

Browser other questions tagged

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