Input valueAsNumber
Every once in a while I learn about a JavaScript property that I wish I had known about years earlier -- 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 parseInt
/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 valueAsNumber
!
One of the web components I've always loved has been Facebook's modal dialog. This "lightbox" isn't like others: no dark overlay, no obnoxious animating to size, and it doesn't try to do "too much." With Facebook's dialog in mind, I've created LightFace: a Facebook lightbox...
In 2001 I had just graduated from a small town high school and headed off to a small town college. I found myself in the quaint computer lab where the substandard computers featured two browsers: Internet Explorer and Mozilla. It was this lab where I fell...
Without a doubt, my least favorite form element is the SELECT
element. The element is almost unstylable, looks different across platforms, has had inconsistent value access, and disaster that is the result of multiple=true
is, well, a disaster. Needless to say, whenever a developer goes...
You've probably noticed that I shy away from writing really long articles. Here are a few reasons why:
Most site visitors are coming from Google and just want a straight to the point, bail-me-out ASAP answer to a question.
I've noticed that I have a hard time...
Great tip! Is there anything wrong with parseInt / parseFloat, apart from the extra line of code? (you labeled it “BAD”)
Depending on lang, decimal separator can be comma. So,
parseFloat('0,01');
will return0
instead of0.01
.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 uNaN
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 onString
types, but the default type of an html input isString
.Bonjour,
parseFloat(string, 10)
vsNumber(string)
…