9

I'm new to web development, and in my function want to check if a given string value is a number. In case the string isn't a valid number I want to return null.

The following works for all cases except when the string is "0" in which case it returns null.

parseInt(columnSortSettings[0]) || null;

How do I prevent this from happening. Apparantly parseInt doesn't consider 0 as an integer!

2
  • 2
    0 is a falsy value .. Commented Sep 24, 2015 at 12:59
  • 2
    I haven't posted this link in a while, but it's always worth a read for anyone learning/using javascript Commented Sep 24, 2015 at 13:35

3 Answers 3

9

Since 0 is act as false , so you can use isNaN() in this case

var res = parseInt(columnSortSettings[0], 10);
return isNaN(res) ? null : res;
Sign up to request clarification or add additional context in comments.

1 Comment

Don't forget the radix.
4

It's because you are basically testing 0 which is also false. You can do

var n = columnSortSettings[0];
if(parseInt(n, 10) || n === '0'){
    //...
}

You can also test instead if it's a number

if(typeof(parseInt(n, 10)) === 'number'){
  //...
}

But beware cause

typeof Infinity === 'number';
typeof NaN === 'number';

3 Comments

Don't forget the radix.
@Andy, yup totally forgot :)
Thanks @Eric . As SO lets me accept only one answer, I've upvoted your answer.
1

You can use the isNumeric operator from rxjs library (importing rxjs/util/isNumeric

Comments

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.