Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to check whether a var is string or number using javascript

I have a variable var number="1234", though the number is a numeric value but it is between "" so when I check it using typeof or by NaN I got it as a string .

function test()
{
    var number="1234"

if(typeof(number)=="string")
{
    alert("string");
}
if(typeof(number)=="number")
{
    alert("number");
}

}

I got always alert("string"), can you please tell me how can I check if this is a number?

like image 977
Romi Avatar asked Jul 23 '11 10:07

Romi


3 Answers

As far I understand your question you are asking for a test to detect if a string represents a numeric value.

A quick test should be

function test() {
   var number="1234"
   return (number==Number(number))?"number":"string"
}

As Number, if called without the new keyword convert the string into a number. If the variable content is untouched (== will cast back the numeric value to a string) you are dealing with a number. It is a string otherwise.

function isNumeric(value) {
   return (value==Number(value))?"number":"string"
}

/* tests evaluating true */
console.log(isNumeric("1234"));  //integer
console.log(isNumeric("1.234")); // float
console.log(isNumeric("12.34e+1")); // scientific notation
console.log(isNumeric(12));     // Integer
console.log(isNumeric(12.7));   // Float
console.log(isNumeric("0x12")); // hex number

/* tests evaluating false */
console.log(isNumeric("1234e"));
console.log(isNumeric("1,234"));
console.log(isNumeric("12.34b+1"));
console.log(isNumeric("x"));
like image 190
Eineki Avatar answered Nov 15 '22 07:11

Eineki


The line

 var number = "1234";

creates a new String object with the value "1234". By putting the value in quotes, you are saying that it a string.

If you want to check if a string only contains numeric digits, you can use regular expressions.

if (number.match(/^-?\d+$/)) {
    alert("It's a whole number!");
} else if (number.match(/^-?\d+*\.\d+$/)) {
    alert("It's a decimal number!");
}

The pattern /^\d+$/ means: at the start (^) of the string, there is an optional minus sign (-?), then a digit (\d), followed by any more digits (+), and then the end of the string ($). The other pattern just looks for a point between the groups of digits.

like image 21
Jeremy Avatar answered Nov 15 '22 06:11

Jeremy


See parseInt and parseFloat

like image 20
spender Avatar answered Nov 15 '22 07:11

spender