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
!
![Regular Expressions for the Rest of Us]()
Sooner or later you'll run across a regular expression. With their cryptic syntax, confusing documentation and massive learning curve, most developers settle for copying and pasting them from StackOverflow and hoping they work. But what if you could decode regular expressions and harness their power? In...
![Serving Fonts from CDN]()
For maximum performance, we all know we must put our assets on CDN (another domain). Along with those assets are custom web fonts. Unfortunately custom web fonts via CDN (or any cross-domain font request) don't work in Firefox or Internet Explorer (correctly so, by spec) though...
![Translate Content with the Google Translate API and JavaScript]()
Note: For this tutorial, I'm using version1 of the Google Translate API. A newer REST-based version is available.
In an ideal world, all websites would have a feature that allowed the user to translate a website into their native language (or even more ideally, translation would be...
![MooTools Typewriter Effect Plugin Upgrade]()
Last week I shared my MooTools Typewriter Class with you. It was pretty well received and I got a few feature requests that I've implemented including "backspacing" and character variance delays. I'm not going to explain the old code, so click here...
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)
…