Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript : check a string for number

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!

like image 331
Rahul Misra Avatar asked Sep 24 '15 12:09

Rahul Misra


People also ask

How do you check if a string contains a number in TypeScript?

To check if a string contains numbers in JavaScript, call the test() method on this regex: /\d/ . test() will return true if the string contains numbers. Otherwise, it will return false .

How do you check if a string contains a number?

To find whether a given string contains a number, convert it to a character array and find whether each character in the array is a digit using the isDigit() method of the Character class.

How do I check if a variable is number or string?

2) Using typeof() The typeof operator returns a string indicating the type of the unevaluated operand. If the variable is type number, it would return the string number . We can use this to determine if the variable is number type. The typeof() performs much better than isNaN() .

How do you check if a string is a number in JS?

In JavaScript, a built-in method isNaN() evaluates the string in such a way that if the passed string is a number. This built-in function of JavaScript returns a true or false output based on the passing string. Furthermore, the “+” operator is employed to check the string by converting the string into a number.


1 Answers

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;
like image 173
Pranav C Balan Avatar answered Oct 08 '22 23:10

Pranav C Balan