396

Is there is any function like isNumeric in pure JavaScript?

I know jQuery has this function to check the integers.

TylerH
  • 20,799
  • 66
  • 75
  • 101
Duke
  • 35,420
  • 13
  • 53
  • 70
  • 4
    Try `value => !isNan(+value)` – Hulke Oct 22 '18 at 08:46
  • 2
    isNaN() https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/isNaN – Joeri Dec 19 '18 at 09:23
  • Wanted to add in isInteger (please note floats are not integers) https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isInteger – Jon Jan 25 '19 at 14:34

6 Answers6

664

There's no isNumeric() type of function, but you could add your own:

function isNumeric(n) {
  return !isNaN(parseFloat(n)) && isFinite(n);
}

NOTE: Since parseInt() is not a proper way to check for numeric it should NOT be used.

Robert Harvey
  • 178,213
  • 47
  • 333
  • 501
Sudhir Bastakoti
  • 99,167
  • 15
  • 158
  • 162
  • 19
    This solution is used in / taken from Jquery library $.isNumeric(obj) http://api.jquery.com/jquery.isnumeric/ – ThdK Jan 12 '15 at 12:12
  • 2
    @Matt My comment was aimed at the comment and the note in the answer stating `parseInt` was the wrong way of doing this (then going ahead and using `parseFloat`, which doesn't really seem different). Interestingly `isFinite` will get you the result you're after in almost all cases on its own (apart from whitespace strings, which for some reason return `true`), so `parseInt` vs `parseFloat` seems irrelevant in this context. I certainly can't find a single input to that function where `parseInt` makes a difference. – Vala Aug 17 '15 at 20:10
  • @Thor84no http://jsfiddle.net/fNPvf/17918/ – Matt Aug 17 '15 at 20:33
  • 1
    I'll grant you the difference on `'.\d+'`, I missed that, but the JS console is more useful than that fiddle. Either way, that's the appropriate answer, not whatever the stuff about short-circuiting `&&`s was about. It does feel like there should be a better way than this though since `isFinite` covers almost everything on its own. I did a fiddle of my own to have a play: http://jsfiddle.net/d5cxdwue/1/ – Vala Aug 17 '15 at 23:31
  • 2
    DON'T USE THIS FUNCTION it does not work with floats. See jQuery's [`isNumeric`](https://github.com/jquery/jquery/blob/bf48c21d225c31f0f9b5441d95f73615ca3dcfdb/src/core.js#L206) here for ideas on implementing it. – tsiege Sep 03 '15 at 19:03
  • isFinite( "0" ) is true.. that's why you should use the more robust Number.isFinite( "0" ) which returns false ;) – faebster Mar 04 '16 at 09:45
  • I would argue though that `Infinity` is numeric though not a number. So if you're using this to sum all the numerics in an array, and one of them is `Infinity`, probably it should be `Infinity`. But of course if there is also a `-Infinity`, you should understandably get NaN (which is what javascript yields.) – user420667 Mar 29 '16 at 18:50
  • 1
    @Thor84no *parseInt* doesn't deal correctly with numbers in their exponential form. Consider following example: parseInt(1000000000000000000000, 10) will return 1, while parseFloat(1000000000000000000000) will return 1e+21, because parseInt try to parse "1e+21" – Eugene Bogomolny Jul 08 '16 at 13:40
  • Since in my case, only integers and floats (non-exponential) are valid, I added this to the top of the function: `if (n.toUpperCase().includes('E')) return false;` This protects against accidental exponents, e.g. 24e4. Technically, this is numeric, but in most front-end apps, an alpha character in a numeric field should trigger a validation error. – CaptainMarvel Aug 24 '16 at 20:17
  • don't work for me. bug for brazilian format. `isNumeric('1,2');` best solution: https://github.com/adamwdraper/Numeral-js – Ilario Junior Nov 01 '17 at 17:58
  • Using `parseFloat()` instead of `Number()` has inconsistent behavior across ECMAScript specifications when parsing exponential notation. In contrast, `Number()` has always been able to handle it. The downside of `Number()` is that the entire string must be numeric, and not just the start of the string. – Patrick Roberts Aug 31 '18 at 18:31
  • This solution will return `true` for `"123a"` and such.. (number with a string). – Hulke Oct 22 '18 at 08:45
  • Don't use this if you want to check that a string is actually, strictly, numeric. Just fixed bugs in my app because a dev must have found this solution (hello there) to validate text input as numeric... but it accepts `123abc` as numeric. – Aaron Beall Mar 27 '19 at 21:51
  • 1
    For future readers, many of the comments above need to be ignored due to them being discussion about one of the earlier edits of this answer (there are 5 atm). I'm using this exact function and am having no issues. `"123a"` returns `false` and as does `"123abs"`. As far as I can tell it works perfectly! – Matthew Ludwig Jul 06 '19 at 03:44
  • 3
    What about `Number.isInteger()`? https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isInteger – kurdtpage Aug 13 '19 at 03:55
  • 6
    Careful. This function returns true for single element arrays containing a numeric element: ```isNumeric([0]) === true``` and ```isNumeric(['123']) === true``` – Timbo White Dec 12 '19 at 20:11
210

This should help:

function isNumber(n) {
  return !isNaN(parseFloat(n)) && isFinite(n);
}

Very good link: Validate decimal numbers in JavaScript - IsNumeric()

Alexander Abakumov
  • 13,617
  • 16
  • 88
  • 129
Tats_innit
  • 33,991
  • 10
  • 71
  • 77
109
function IsNumeric(val) {
    return Number(parseFloat(val)) === val;
}
Jonathan Schneider
  • 26,852
  • 13
  • 75
  • 99
Ali Humayun
  • 1,756
  • 1
  • 15
  • 12
  • 7
    I think the updated version of this is actually the best answer here. I find it odd that it has the least up-votes. I thought at first that it might fail if `IsNumeric` was called with `NaN`, but due to the quirk of NaN that it's not equal to anything it actually works out fine. – Vala Dec 04 '14 at 11:31
  • 4
    And I think you can also drop the cast to `Number()` and rely on the double equals to do a bit of conversion: `let isNumeric = (val) => parseFloat(val) == val;` – Mark Birbeck Aug 31 '16 at 11:40
  • As per my requirement which I believe many other developers would have it should be function IsNumeric(val) { return Number(val)==val; } So that it ignores in case of empty string. Because I only want to validate if there is invalid value entered. While allowing empty string which is not number. I think all three answers are good based on scenarios – Ali Humayun Sep 01 '16 at 22:40
  • Explain the code please. Why not `Number(val).toString() == val.toString()`? – x-yuri Apr 15 '18 at 00:11
  • 1
    if Val is undefined then .ToString will throw exception – Ali Humayun May 10 '18 at 15:12
  • I'm not sure I'm getting this answer. The string "96" is not numeric because Number("96") does not strictly equal "96". Shouldn't it be numeric? – Pierre Arlaud Jan 02 '19 at 15:56
  • You can try As per my requirement which I believe many other developers would have it should be function IsNumeric(val) { return Number(val)==val; } So that it ignores in case of empty string. Because I only want to validate if there is invalid value entered. While allowing empty string which is not number. I think all three answers are good based on scenarios – Ali Humayun Jan 03 '19 at 07:50
  • It is bad practice to check equals on two floating point numbers – Phil M Sep 17 '19 at 17:13
22

There is Javascript function isNaN which will do that.

isNaN(90)
=>false

so you can check numeric by

!isNaN(90)
=>true
Sophie Alpert
  • 139,698
  • 36
  • 220
  • 238
Soundar Rathinasamy
  • 6,658
  • 6
  • 29
  • 47
19
var str = 'test343',
    isNumeric = /^[-+]?(\d+|\d+\.\d*|\d*\.\d+)$/;

isNumeric.test(str);
ryan
  • 215
  • 2
  • 4
  • 6
    Well, depending on the use case, it might actually be the worst answer here. For example, this returns `false` against `' 1'` or `'0x01'`, localization is not taken into account... – Eric Redon Jul 25 '14 at 20:49
  • 1
    I kinda like this answer better, if you are reading chunks from a string or an user input, isNaN and parseInt can result in unwanted false positives like "123abc", "2e1", "0x2", etc.. (even jQuery.isNumeric will parse true). I would use something like this `function isNumeric(str) { return /^\d*\.{0,1}\d*$/.test(str); }` – ebob May 01 '17 at 19:19
  • 3
    Well, depending on the use case, it might actually be the best answer here. – Zephyr was a Friend of Mine Dec 20 '17 at 19:19
  • As long as you trim strings and aren't worried about alternative representations this is a reasonable answer. – Matt Sanders May 15 '19 at 18:37
12

isFinite(String(n)) returns true for n=0 or '0', '1.1' or 1.1,

but false for '1 dog' or '1,2,3,4', +- Infinity and any NaN values.

kennebec
  • 102,654
  • 32
  • 106
  • 127