javascript tofixed decimal places doesn't work

后端 未结 1 758
猫巷女王i
猫巷女王i 2021-01-29 11:07

What\'s the error in my script? It must have something do to with tofixed, not sure if it\'s the right place where it should be?

The rounding seems like to not work. St

1条回答
  •  情书的邮戳
    2021-01-29 11:40

    You're calling toFixed on the result of parseFloat(value3), and then using that as the right-hand operand of * — turning it back into a number again. Then you're taking the number resulting from the multiplication and assigning it to innerHTML, which turns it into a string using the default toString.

    You probably meant to apply toFixed(2) to the overall result:

    document.getElementById('result1').innerHTML = ((parseFloat(value1) + parseFloat(value2)) * parseFloat(value3)).toFixed(2);
    // --------------------------------------------^--------------------------------------------------------------^
    

    function output() {
      var value1 = document.getElementById('value1').value;
      var value2 = document.getElementById('value2').value;
      var value3 = document.getElementById('value3').value;
      document.getElementById('result1').innerHTML = ((parseFloat(value1) + parseFloat(value2)) / parseFloat(value3)).toFixed(2);
    }
    
     + 
    
     / 
    
    

    0 讨论(0)
提交回复
热议问题