12

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?

6
  • possible duplicate of Validate numbers in JavaScript - IsNumeric() Commented Feb 28, 2014 at 16:24
  • Is "3 " a number or not for you ? If so the linked question's accepted answer isn't correct. Commented Feb 28, 2014 at 16:46
  • Rejecting "3 " is feasable. If one likes to accept, it can be trimmed first. Commented Feb 28, 2014 at 16:50
  • What about numbers that don't fit in JS numbers (for example "12345678901234567") ? Commented Feb 28, 2014 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. Commented Feb 28, 2014 at 17:18

9 Answers 9

18

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);
}    
Sign up to request clarification or add additional context in comments.

3 Comments

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.
A clarification: this function will return true if the string contains at least 1 number, not that it contains only numbers.
In both, the cases above function is returning true only
4

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}$/;

7 Comments

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...
Note that this would accept numbers that don't fit in a JS number. This may, or not, be desirable.
And it doesn't accept negative numbers. This is easy to fix, though.
In fact, a lot of fixes are necessary, for example for "-1e3".
Not everybody uses , and . that way; some of the world does it the opposite way. Not everybody uses groups of 3 digits.
|
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);

2 Comments

Looks good... Rejects empty, tailing and whitespace strings, accepts non-canonical floats like '.0' or '0.0', and even elaborate ones as 1e5. Cool!
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.
2

You can always do:

function isNumber(n)
{
    if (n.trim().length === 0)
        return false;
    return !isNaN(n);
}

3 Comments

Would evaluate true for all longer whitespace inputs.
@dronus you're right, i didn't think of it, doing a trim solved the problem
!isNaN(s) is what I came for
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.

Comments

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

Comments

0

Here is a solution that will work in almost any language, environment, and character set:

let input = "-1.75"; //this is the string inputted
let theStr = input; //it's good practice not to edit the input directly
let isNum = true;
let theseAreNumbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];

let possibleNegative = false;
if(theStr.indexOf("-") == 0){ //if the first character is a minus sign, take it out and add it back in at the end if everything else looks like a number
  possibleNegative = true;
  theStr = theStr.slice(1, theStr.length);
}

let possibleFloat = false; //this code is doubled just to account for floats -_-'
if(theStr.indexOf(".") >= 0){ //split into both sides of possible decimal point
   theStr = theStr.split(".");
   possibleFloat = true;
}

if(theStr.length == 0){
   isNum = false;
} else if(possibleFloat && theStr.length == 2){ //length has to be 2 else "2.72.1" would be counted as a number
   for(i = 0; i < theStr.length; i++){
      for(k = 0; k < theStr[i].length; k++){
         for(j = 0; j < 10; j++){
            if(theStr[i][k] == theseAreNumbers[j] && theStr[i][k] != " "){ //space is counted as 0 sometimes
               j = 10;
            }
            if(j == 9){
               isNum = false;
               k = theStr[i].length;
            }
         }
      }
   }
} else if(!possibleFloat){ //just this if is needed if you only want positive ints
   for(i = 0; i < theStr.length; i++){
      for(j = 0; j < 10; j++){
         if(theStr[i] == theseAreNumbers[j] && theStr[i] != " "){
            j = 10;
         }
         if(j == 9){
            isNum = false;
            i = theStr.length;
         }
      }
   }
} else {
  isNum = false;
}

let theNum = theStr;
if(possibleFloat){
   theNum = theStr[0] + "." + theStr[1];
}
if(possibleNegative){
  theNum = "-" + theNum;
}
if(isNum){
   console.log("Input is a number! and that number is: " + theNum);
}else{
   console.log("That's no number!");
}

Comments

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

Comments

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

4 Comments

If the string has only whitespace characters, the second == will pass.
Doesn't work for ' '. That's why I deleted my answer.
Argh... what a mess :-)
This would be corrected by ""+(+n)===n. However, this enforces a very canonical number input, eg. '0.123' would be ok while '.123' would fail.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.