An Interest In:
Web News this Week
- April 15, 2024
- April 14, 2024
- April 13, 2024
- April 12, 2024
- April 11, 2024
- April 10, 2024
- April 9, 2024
April 19, 2022 09:45 pm GMT
Original Link: https://dev.to/aretecore/alternative-to-parseint-inputvalueasnumber-12l
Alternative to parseInt() - input.valueAsNumber
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.
Original Link: https://dev.to/aretecore/alternative-to-parseint-inputvalueasnumber-12l
Share this article:
Tweet
View Full Article
Dev To
An online community for sharing and discovering great ideas, having debates, and making friendsMore About this Source Visit Dev To