10

I don't get how hard it is to discern a string containing a number from other strings in JavaScript.

Number('') evaluates to 0, while '' is definitely not a number for humans.

parseFloat enforces numbers, but allow them to be tailed by abitrary text.

isNaN evaluates to false for whitespace strings.

So what is the programatically function for checking if a string is a number according to a simple and sane definition what a number is?

dronus
  • 10,774
  • 8
  • 54
  • 80
  • possible duplicate of [Validate numbers in JavaScript - IsNumeric()](http://stackoverflow.com/questions/18082/validate-numbers-in-javascript-isnumeric) – cookie monster Feb 28 '14 at 16:24
  • Is `"3 "` a number or not for you ? If so the linked question's accepted answer isn't correct. – Denys Séguret Feb 28 '14 at 16:46
  • Rejecting "3 " is feasable. If one likes to accept, it can be trimmed first. – dronus Feb 28 '14 at 16:50
  • What about numbers that don't fit in JS numbers (for example "12345678901234567") ? – Denys Séguret Feb 28 '14 at 16:54
  • @dronus, some context as far as where you are getting this number from and what you will be doing with it might be helpful if you want a very specific answer. – Smern Feb 28 '14 at 17:18
  • Mostly I like to check data send by some JS script to another script. Doing so I can assume the float number string is canonically formed. On the other hand, I like to trap any occurence of a non-number to make further processing sane. So an empty string, an string containing error messages, and even a number tailed by text definitely points to some problem at the sending scripts side, the transmission, or some manipulation inbetween, and should be rejected. – dronus Feb 28 '14 at 23:29

8 Answers8

17

By using below function we can test whether a javascript string contains a number or not. In above function inplace of t, we need to pass our javascript string as a parameter, then the function will return either true or false

function hasNumbers(t)
{
var regex = /\d/g;
return regex.test(t);
}    
Sandeep
  • 1,504
  • 7
  • 22
  • 32
Ramu Vemula
  • 197
  • 1
  • 4
  • By using above function we can test whether a javascript string contains a number or not. In above function inplace of t, we need to pass our javscript string as a parameter, then the function will return either true or false. – Ramu Vemula Mar 18 '16 at 06:49
  • A clarification: this function will return true if the string contains *at least 1 number*, not that it contains *only numbers*. – Joel L Jan 31 '19 at 10:29
  • In both, the cases above function is returning true only – SUNIL JADHAV Apr 22 '20 at 13:34
3

If you want something a little more complex regarding format, you could use regex, something like this:

var pattern = /^(0|[1-9][0-9]{0,2}(?:(,[0-9]{3})*|[0-9]*))(\.[0-9]+){0,1}$/;

Demo

enter image description here

I created this regex while answering a different question awhile back (see here). This will check that it is a number with atleast one character, cannot start with 0 unless it is 0 (or 0.[othernumbers]). Cannot have decimal unless there are digits after the decimal, may or may not have commas.. but if it does it makes sure they are 3 digits apart, etc. Could also add a -? at the beginning if you want to allow negative numbers... something like:

/^(-)?(0|[1-9][0-9]{0,2}(?:(,[0-9]{3})*|[0-9]*))(\.[0-9]+){0,1}$/;
Community
  • 1
  • 1
Smern
  • 18,746
  • 21
  • 72
  • 90
  • 1
    A straight forward solution, and adaptable to all number formats one would like to allow. On the other hand, quite elaborate for just checking a number... – dronus Feb 28 '14 at 16:38
  • Note that this would accept numbers that don't fit in a JS number. This may, or not, be desirable. – Denys Séguret Feb 28 '14 at 16:59
  • And it doesn't accept negative numbers. This is easy to fix, though. – Denys Séguret Feb 28 '14 at 17:00
  • 1
    In fact, a lot of fixes are necessary, for example for `"-1e3"`. – Denys Séguret Feb 28 '14 at 17:00
  • The bottom of my post accounts for negative numbers, could do a similar fix for `e`. Depends on the use cases but this works well for most typical user inputs. – Smern Feb 28 '14 at 17:15
  • 1
    Not everybody uses `,` and `.` that way; some of the world does it the opposite way. Not everybody uses groups of 3 digits. – Pointy Feb 28 '14 at 17:28
  • @Pointy, I was addressing what the majority would typically consider to be normal properly formatted numbers since the OP stated he is concerned with "a simple and sane definition what a number is" which I suppose is sort of ambiguous... but this can easily be modified to meet a requirement change such as you mentioned, so I don't think the concerns are that great. – Smern Feb 28 '14 at 18:31
2

There's this simple solution :

var ok = parseFloat(s)==s;

If you need to consider "2 " as not a number, then you might use this one :

var ok = !!(+s==s && s.length && s.trim()==s);
Denys Séguret
  • 372,613
  • 87
  • 782
  • 758
  • Looks good... Rejects empty, tailing and whitespace strings, accepts non-canonical floats like `'.0'` or `'0.0'`, and even elaborate ones as `1e5`. Cool! – dronus Feb 28 '14 at 16:49
  • Thats exhausting. Maybe I give up and go with this solution anyway. I will also post my 'exact' solution, that enforces a canonical form of the number, which may make problems, but should be ok in my case. – dronus Feb 28 '14 at 23:34
2

You can always do:

function isNumber(n)
{
    if (n.trim().length === 0)
        return false;
    return !isNaN(n);
}
Shryme
  • 1,572
  • 1
  • 14
  • 22
1

Let's try

""+(+n)===n

which enforces a very rigid canonical way of the number.

However, such number strings can be created by var n=''+some_number by JS reliable.

So this solution would reject '.01', and reject all simple numbers that JS would stringify with exponent, also reject all exponential representations that JS would display with mantissa only. But as long we stay in integer and low float number ranges, it should work with otherwise supplied numbers to.

dronus
  • 10,774
  • 8
  • 54
  • 80
1

No need to panic just use this snippet if name String Contains only numbers or text. try below.

var pattern = /^([^0-9]*)$/;
if(!YourNiceVariable.value.match(pattern))   {//it happen while Name Contains only Charectors.}

if(YourNiceVariable.value.match(pattern))   {//it happen while Name Contains only Numbers.}
-1

This might be insane depending on the length of your string, but you could split it into an array of individual characters and then test each character with isNaN to determine if it's a number or not.

Scott
  • 2,753
  • 1
  • 24
  • 31
-1

A very short, wrong but correctable answer was just deleted. I just could comment it, besides it was very cool! So here the corrected term again:

n!=='' && +n==n'

seems good. The first term eliminates the empty string case, the second one enforces the string interpretataion of a number created by numeric interpretation of the string to match the string. As the string is not empty, any tolerated character like whitespaces are removed, so we check if they were present.

dronus
  • 10,774
  • 8
  • 54
  • 80