valueAsNumber is one of them. The
valueAsNumber provides the value of an
input[type=number] as a Number type, instead of the traditional string representation when you get the value:
/* Assuming an <input type="number" value="1.234" /> */ // BAD: Get the value and convert the number input.value // "1.234" const numberValue = parseFloat(input.value, 10); // GOOD: Use valueAsNumber input.valueAsNumber // 1.234
This property allows us to avoid
parseFloat, but one gotcha with
valueAsNumber is that it will return
NaN if the
input is empty.
Thank you to Steve Sewell for making me aware of
PSA: number inputs have a `.valueAsNumber` property that you may find handy pic.twitter.com/1QwdAW16CC— Steve Sewell (@Steve8708) March 31, 2022
Great tip! Is there anything wrong with parseInt / parseFloat, apart from the extra line of code? (you labeled it “BAD”)
Leaving this here hoping it saves some time I wish I had saved to some other person looking for an answer…
If you’re using this on an html input, maybe with angular… it works great, but you NEED to add the ‘type=”number”‘ to your input or it will keep giving u NaN no matter what’s in the input box.
The reason ?
for some reason that I am not looking up at this time, valueAsNumber does NOT work on String types, but the default type of an html input is String.