" or "<" to judge whether a number is greater than 0 or less than 0, and then determine whether a number is positive or negative; 2. Use the sign() of the Math object Method, syntax "Math.sign(value)"."/> " or "<" to judge whether a number is greater than 0 or less than 0, and then determine whether a number is positive or negative; 2. Use the sign() of the Math object Method, syntax "Math.sign(value)".">

Home  >  Article  >  Web Front-end  >  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

青灯夜游
青灯夜游Original
2021-07-20 13:58:3511241browse

JavaScript method to determine whether a positive number or a negative number: 1. Use the comparison operator ">" or "2539c73d84922fdbbe2c9fa449999548” or “3d83139c05fb92c81136398455cf314c

If the first operand is greater than the second operand, return true; otherwise return falseExample:

var a=1;
if(a>0){
 console.log("正数");
}else if(a<0){
console.log("负数");
}else{
console.log("都不是");
}

Output:


正数

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);

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.

Example:


const positive = 5;
const negative = -5;
const zero = 0;
Math.sign(positive); // 1
Math.sign(negative); // -1
Math.sign(zero); // 0

[Recommended learning:

javascript advanced tutorial]

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!

Statement:
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