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!
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!
Share Improve this question edited Feb 19, 2018 at 16:16 Rahul Misra asked Sep 24, 2015 at 12:56 Rahul MisraRahul Misra 6692 gold badges8 silver badges16 bronze badges 2 |3 Answers
Reset to default 9Since 0
is act as false , so you can use isNaN()
in this case
var res = parseInt(columnSortSettings[0], 10);
return isNaN(res) ? null : res;
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';
You can use the isNumeric operator from rxjs library (importing rxjs/util/isNumeric
0
is a falsy value .. – Hacketo Commented Sep 24, 2015 at 12:59