Search code examples
javascripthtmlhtml-input

Loss of Decimal Value when taking number from form input


I am trying to take a value (up to 2 decimal places) from an HTML form Input and then I plan to use that value for some calculations in JavaScript.

The problem i have is when a user inputs in a value, the decimal places are lost.

I have simplified the code below to highlight the issue.

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<body>
  <form>
    1st Number<br> <input type="number" step="0.01" id="num1" placeholder=0.00>
  </form>

  <button onclick="calculator()">submit</button>

  <p id="answer"></p>
</body>

<script>
        function calculator(){
            const num1 = document.getElementById("num1").value|0;
            document.getElementById("answer").innerHTML = num1; 
//example user inputs 5.55, the returned value = 5
        }
</script>
</html>

appreciate any guidance on this


Solution

  • You weren't using the proper operator for logical OR, which is || (logical) not | (bitwise).

    Also, you should use .textContent instead of .innerHTML to set the value into another element since the value retrieved won't contain any HTML. .innerHTML has security and performance implications.

    <!DOCTYPE html>
    <html lang="en">
    <head>
      <meta charset="UTF-8">
      <meta name="viewport" content="width=device-width, initial-scale=1.0">
      <title>Document</title>
    </head>
    <body>
      <form>
        1st Number<br> <input type="number" step="0.01" id="num1" placeholder=0.00>
      </form>
    
      <button onclick="calculator()">submit</button>
    
      <p id="answer"></p>
    </body>
    
    <script>
            function calculator(){
                const num1 = document.getElementById("num1").value || 0;
                document.getElementById("answer").textContent = num1; 
            }
    </script>
    </html>