Input valueAsNumber

By  on  

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!

Recent Features

  • By
    5 Ways that CSS and JavaScript Interact That You May Not Know About

    CSS and JavaScript:  the lines seemingly get blurred by each browser release.  They have always done a very different job but in the end they are both front-end technologies so they need do need to work closely.  We have our .js files and our .css, but...

  • By
    39 Shirts &#8211; Leaving Mozilla

    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...

Incredible Demos

  • By
    PHP / MooTools 1.2 Accordion Helper

    The MooTools Accordion plugin seems to be the plugin that people seem to have the most problems with. It's an awesome plugin, so I can see why so many people want to use it, but I think that may be part of the problem.

  • By
    HTML5&#8217;s placeholder Attribute

    HTML5 has introduced many features to the browser;  some HTML-based, some in the form of JavaScript APIs, but all of them useful.  One of my favorites if the introduction of the placeholder attribute to INPUT elements.  The placeholder attribute shows text in a field until the...

Discussion

  1. Martin

    Great tip! Is there anything wrong with parseInt / parseFloat, apart from the extra line of code? (you labeled it “BAD”)

    • Kyryl

      Depending on lang, decimal separator can be comma. So, parseFloat('0,01'); will return 0 instead of 0.01.

  2. yann

    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.

  3. Bonjour,

    parseFloat(string, 10) vs Number(string)

Wrap your code in <pre class="{language}"></pre> tags, link to a GitHub gist, JSFiddle fiddle, or CodePen pen to embed!