1

I have this very basic calculator:

<html>
    <body>
        <form name="form">
            <input type="text" name="num1" />
            <input type="text" name="num2" />
            <input type="text" name="res" />
            <input type="button" value="+" onclick="form.res.value = form.num1.value + form.num2.value" />
        </form>
    </body>
</html>

But it treats form.num1.value and form.num2.value as string and because of it the result is the concatenation of these values instead of addition.

How to treat them as numbers?

Billie
  • 8,528
  • 12
  • 35
  • 64

4 Answers4

5

Wrap each value in a parseInt(value, 10) or parseFloat(value).

Daniel A. White
  • 181,601
  • 45
  • 354
  • 430
2

Shortest way is the unary plus operator, which converts to Number:

+form.num1.value + +form.num2.value

Note: it will return NaN for mixed inputs like "10 potatoes". To avoid that, you can use parseInt or parseFloat.

Community
  • 1
  • 1
bfavaretto
  • 70,503
  • 15
  • 107
  • 148
1

Try to convert them to number like this:

onclick="Numberform.res.value = Number(form.num1.value) + Number(form.num2.value)"
Shryme
  • 1,552
  • 1
  • 14
  • 22
1

Convert them to numbers with the + operator or parseFloat.

Poetro
  • 574
  • 3
  • 9