The problem with HTML inputs is even number type inputs (<input type="number">
) return strings when called. Due to JavaScripts untyped syntax, weird things can happen with strings unless you add the safety net of using parseInt()
or parseFloat()
.
I recently found a cool little alternative, input.valueAsNumber
! Awesomely, valueAsNumber
will return a primitive number
regardless of whether the input is 3
or 3.14
(integer or float) which can save you an extra step.
Here is some basic syntax:
console.log(input.valueAsNumber)
// 3.14, not "3.14" π
There is one slight caveat - if the input is empty, valueAsNumber
will return NaN
, so just beware of that.
Top comments (0)