0

I am receiving var value by:

var val=document.getElementById('ctl00_ContentPlaceHoldermain_TextBox1').value;

In my code I am checking type of each character using 'typeof'. But always it is returning string only. How to identify the number?

Jeremy Rajan
  • 662
  • 3
  • 12
Sachin
  • 21
  • 6
  • Possible duplicate of [Validate decimal numbers in JavaScript - IsNumeric()](http://stackoverflow.com/questions/18082/validate-decimal-numbers-in-javascript-isnumeric) – Rajesh Feb 25 '16 at 06:14
  • 1
    isNaN is a JavaScript function to let you know if a string is not a number. https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/isNaN – Than Ngo Hoai Feb 25 '16 at 06:17

2 Answers2

2

You can use parseInt or parseFloat. If parseInt(str) returns NaN so your string is not a number.

You can use only for strings that contains only digits: parseInt('123'). If it possible that your string can contains letters too so you can get some problems:

parseInt('123') // -> 123
parseInt('123asd') // '123asd' is not a number but parseInt returns 123

So more simple way is to use jQuery's isNumeric function or implement it by yourself

You can see more about it from the link in the @Rahat's comment.

Also you can see at this blog post

Glorfindel
  • 21,988
  • 13
  • 81
  • 109
feeeper
  • 2,865
  • 4
  • 28
  • 42
  • You should not use parseInt or parseFloat for this purpose. Reason explained here: http://stackoverflow.com/questions/9716468/is-there-any-function-like-isnumeric-in-javascript-to-validate-numbers – Rahatur Feb 25 '16 at 06:18
  • I have to select each element from the val and need to identify whether it is number or not? @Rahat – Sachin Feb 25 '16 at 06:53
  • @Sachin No, you just can use `isNaN` function as @ThanNgoHoai mentioned earlier (http://stackoverflow.com/questions/35619682/how-to-identify-a-number-from-a-var-value/35619712?noredirect=1#comment58922084_35619682) – feeeper Feb 25 '16 at 07:01
0

I agree with alternative answer but I think parseInt and parseFloat should be used for parsing because they are meant for it. isNaN function can give you numeric checking functionality.

function isNumber(val) {
  if(val == "") {
    return false;
  }
  return !isNaN(val);
}

As per comment, if you want to select number from array then you can simply create loop and call it inside. e.g

var vals = ['dsds','2','','4'];
for (var i = 0; i<vals.length; i++) {
  if(isNumber(vals[i]) {
    // it's number
  }
  else {
    // it's not number;
  }
}
Imad
  • 7,126
  • 12
  • 55
  • 112