- value: The value to check, can be a string or a number.
The Math.sign() function answers whether a number is negative or not by the returned value. If the returned value is 1, then it is not negative. Otherwise, the returned value is -1 indicates that the number passed to the function is a negative number. For example:
// Check if a string is a negative number let string = "-123456"; console.log(Math.sign(string)); // Check if a number is a negative number let number = -123456; console.log(Math.sign(number));
This method is easy to understand. As long as the string (or number) we are checking is a valid negative number, the method returns -1. That is exactly the value we are looking for. In addition, if the string is “0” or the number is zero, this method will return 0.
Using binary < operator
a < 0
- a: The value to be checked can be in type number or string.
We have learned in our school that any negative number is smaller than zero. Hence we can use the smaller than (<) operator to check if that value is a negative number or not. For instance:
// Check if a string is a negative number var string = "-123456"; console.log(string<0); // Check if a number is a negative number var number = -123456; console.log(number<0);
As you can see, using this operator is familiar to you because this math operator has been used many times in practice. You should also know that most programmers enjoy using this solution more than others. However, there are still some other approaches to solve this problem, but we don’t recommend you use them because the solutions provided in this tutorial are the most optimized ones.
Maybe you are interested:
Name of the university: HCMUT