How to check for a number in JavaScript

How to check for a number in JavaScript

Numbers are a primitive type in JavaScript, but just using typeof will not differentiate numbers from NaN or Infinity.

Image for postPhoto by Alex Chambers on Unsplash

It is useful to know how to check if a value is of the primitive type number, since JavaScript is a dynamically typed language.

The easiest way to check for a number is using typeof, which will return the string “number” for any value of the number primitive type, including NaN, Infinity, and -Infinity.

One example when a number might show up as another type, indicating a bug in my code, would be in parsing currency:

In this case, I would know that I forgot to parse the string into a number when I get the value of ?string? back from typeof.

Image for postPhoto by Samuel Zeller on Unsplash

Catching a failed parse

If I use parseFloat() to check the currency value, but I forgot to strip the currency symbol, I get a failed parse and an odd result:

Oh, no. In this case, it looks like typeof is not working how I expected ? because NaN values are considered numbers in JavaScript.

Image for postPhoto by Gemma Evans on Unsplash

When the typeof keyword returns ?number?

An obvious solution to check for the number primitive type is to use the typeof keyword, as I showed above.

But typeof is an incomplete solution, because of two special values in JavaScript: NaN (?Not a Number?) and Infinity.

For my currency example, I know I have a bug if my monetary value is NaN or Infinity, but typeof returns “number” for both these values.

Perhaps my input was written using a currency symbol, and I simply tried to use parseFloat() to capture the value. That would result in NaN:

Image for postPhoto by Timo Kaiser on Unsplash

A custom isNumber() function

Arobust, custom isNumber() function would use typeof to check for the primitive type, check for NaN values, and check for Infinity:

Or, in the case where one is confident that NaN and Infinity are not going to come up, just checking that typeof===”number” would be enough.

Image for postPhoto by ?? Claudio Schwarz | @purzlbaum on Unsplash

The one-liner

I love one-liners. I think they need to be documented with comments, but I think they are actually really useful, not just fancy.

Here is the one-liner for how to check for a number in JavaScript:

But, there is a better way to check for a finite number in JavaScript ? the helper function Number.isFinite() has the same behavior as the custom isNumber() function I wrote. I include an example in the next section.

Image for postPhoto by Bernard Hermant on Unsplash

The easiest way to check for a number: Number.isFinite()

It is actually unnecessary to write custom functions to check for a number, though it is an instructive way to remember that the JavaScript values Infinity, -Infinity, and NaN are all of the number primitive type.

?The Number.isFinite() method determines whether the passed value is a finite number.? ? MDN Docs

The Number.isFinite() method will return true for finite numbers, and false for Infinity, -Infinity, and NaN ? exactly what we want:

There is also the global isFinite() function, which will perform type coercion (such as coercing strings to numbers), as shown above.

I discuss these methods in depth in my article on Infinity in The Startup:

What is Infinity in JavaScript? ??

Infinity is indeed a value in JavaScript, representing mathematical infinity (?). Be prepared for when it pops ups in?

medium.com

Image for postPhoto by Bogomil Mihaylov on Unsplash

Check if a variable is an integer

To check if variable A is an integer I could use the loose equality operator == to see if the parsed value equals itself.

The following code snippet gives an example of how to check for an integer:

Using typeof would differentiate a string that is being coerced into a number from an actual number, as would the strict equality operator ===.

Image for postPhoto by Markus Spiske on Unsplash

Strip out currency symbols

For a better, more robust function, I might want to strip out currency symbols (such as the dollar sign and any commas) first.

Thoroughly parsing money using regular expressions in JavaScript is beyond the scope of this article, but this code removes $ and , before parsing:

Note that the global functions parseInt() and parseFloat() will coerce values to strings, if necessary, and will return NaN if coercion fails.

There are also the functions Numbers.parseInt() and Number.parseFloat(), which have the same exact behavior.

According to the MDN Docs, those duplicate functions were added to ECMAScript 2015 for the ?purpose [of] modularization of globals.?

Image for postPhoto by Toa Heftiba on Unsplash

Does JavaScript actually have separate integers?

No, JavaScript only has one type of number, which is represented internally as a 64-bit floating point representation.

That floating point is the primitive data type number, and there is also a type called BigInt that can be used for arbitrarily large numbers.

The global functions parseInt() and parseFloat() differ in what they expect and will output, but not because there are actually separate integer and floating point types in JavaScript.

Image for postPhoto by Volkan Olmez on Unsplash

Conclusion

Checking for a number in JavaScript is not particularly complicated ? typeof works basically how it should, as long as one is aware that both NaN and Infinity have the typeof number.

The easiest way to check for a finite number (i.e. not NaN or Infinity) in JavaScript is using Number.isFinite(), which does not coerce values to numbers, or the global isFinite(), which does perform type coercion.

Checking for an integer specifically involves using the parseInt() function, followed by comparing the parsed value to itself using == (which will type coerce non-number values, such as strings to numbers) or === (which will only return true if both values are numbers).

Under the hood, integers and floats are all the same: JavaScript only has one type of number, the number primitive type.

Image for postPhoto by K. Mitch Hodge on Unsplash

Further reading

  • The function Number.isInteger() does not coerce strings to numbers:

Number.isInteger()

The Number.isInteger() method determines whether the passed value is an integer. Number.isInteger(value) The value to?

developer.mozilla.org

  • Sumit Kumar Pradhan wrote about checking for numbers on Dev.to:

Check If Variable Is A Number In JavaScript

Post Link : Check If Variable Is A Number In JavaScript This tutorial explains how to check variable is a number in?

dev.to

  • Chris Ferdinandi discussing parsing numbers on his vanilla JS blog:

Converting strings to numbers with vanilla JavaScript

In JavaScript, you can represent a number is an actual number (ex. 42), or as a string (ex. ’42’). If you were to use a?

gomakethings.com

  • The regular expression ^[0?9]+(.[0?9]{1,2})?$ matches money:

Money and only money ? Regex Tester/Debugger

Regular Expression to

www.regextester.com

  • Sarah Dayan wrote about parsing money in JavaScript on frontstuff:

How to Handle Monetary Values in JavaScript | frontstuff

Money is everywhere. Banking apps, e-commerce websites, stock exchange platforms, we interact with money daily. We also?

frontstuff.io

Image for postPhoto by Alejandro Ortiz on Unsplash

21