Home >
Web Front-end >
JS Tutorial >
How to determine whether a positive number or a negative number in JavaScript
How to determine whether a positive number or a negative number in JavaScript
青灯夜游
Release: 2023-01-07 11:44:24
Original
11253 people have browsed it
JavaScript method to determine whether a positive number or a negative number: 1. Use the comparison operator ">" or "<" to determine whether a number is greater than 0 or less than 0, and then determine whether a positive number or a negative number; 2 , Use the sign() method of the Math object, the syntax is "Math.sign(value)".
The operating environment of this tutorial: windows7 system, javascript version 1.8.5, Dell G3 computer.
Method 1: Use comparison operator “>” or “<”
##Comparison operator
Description
<
If the first operand is less than the second operand, return true; otherwise return false
>
If the first operand is greater than the second operand, return true; otherwise return false
Example:
var a=1;
if(a>0){
console.log("正数");
}else if(a<0){
console.log("负数");
}else{
console.log("都不是");
}
Copy after login
Output:
正数
Copy after login
Method 2: Use Math.sign()
Math.sign() function returns a number Sign, indicating whether the number is positive, negative, or zero. Syntax
Math.sign(x);
Copy after login
Parameters
x: It can be any number.
Description:
Because sign is a static method of Math, you should use Math.sign() instead as a member of a Math object you create. method (Math is not a constructor).
rather than as a method on the Math object you create (Math is not a constructor).
This function has 5 return values, namely 1, -1, 0, -0, and NaN; each represents a positive number, a negative number, positive zero, negative zero, and NaN.
The parameters passed into this function will be implicitly converted to numeric types.
The above is the detailed content of How to determine whether a positive number or a negative number in JavaScript. For more information, please follow other related articles on the PHP Chinese website!
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn