0

I'm currently making a simple calculator for use in an intro to Javascript lesson. I would like to know if there's a simpler way of taking the value from a HTML input textbox as an integer than having to use the Javascript parse() method?

HTML:

<input type = "Text" id="num1">

JS:

var num1 = parseInt(document.getElementById("num1").value);
user3765493
  • 3
  • 1
  • 2

1 Answers1

1

You can force a string to be a 32-bit integer like this:

var num1 = ~~document.getElementById("num1").value;

You can, alternatively, accept a number with a possible fractional part with

var num1 = +document.getElementById("num1").value;

In both cases, you can check to see if the original string really did look like a number by using isNaN():

if (isNaN(num1)) {
  // bad input
}
Pointy
  • 405,095
  • 59
  • 585
  • 614