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?
9 Answers 9
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);
}
3 Comments
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}$/;
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
"-1e3"., and . that way; some of the world does it the opposite way. Not everybody uses groups of 3 digits.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
'.0' or '0.0', and even elaborate ones as 1e5. Cool!You can always do:
function isNumber(n)
{
if (n.trim().length === 0)
return false;
return !isNaN(n);
}
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
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
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
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
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
== will pass.' '. That's why I deleted my answer.""+(+n)===n. However, this enforces a very canonical number input, eg. '0.123' would be ok while '.123' would fail.
"3 "a number or not for you ? If so the linked question's accepted answer isn't correct.