Math sign in javascript

# Math.sign: How to Check if a Number is Positive or Negative in JavaScript

Determining the sign of a number is super easy now with ES6’s Math.sign πŸ‘ It will indicate whether the number is positive, negative or zero.

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

# Math.sign Return Value

Math.sign() has 5 possible return values:

1 // positive number -1 // negative number 0 // positive zero -0 // negative zero NaN // not a number 
Math.sign(8); // 1 Math.sign(-8); // -1 Math.sign(0); // 0 Math.sign(-0); // -0 Math.sign(NaN); // NaN Math.sign('hello'); // NaN Math.sign(); //NaN 

Note, the argument passed to this function will be converted to number type implicitly.

Π§ΠΈΡ‚Π°ΠΉΡ‚Π΅ Ρ‚Π°ΠΊΠΆΠ΅:  Php email check error

# Math.sign Gotcha

A common gotcha is thinking that Math.sign return the converted argument value. Math.sign returns only the sign of a number. It doesn’t return the value.

Math.sign(-8); // βœ… return -1 // ❌ It doesn't return -8 

# Math.sign vs Comparative Operator

Got a real good question from the community:

Why use Math.sign when I can use the comparative operator?

if (number > 0)  // Positive > else  // Negative > 
if (Math.sign(number) > 0)  // Positive > else  // Negative > 

Indeed, if you’re just checking the boolean status, then I’d just use the comparative operator instead of using Math.sign . But where Math.sign shines is it returns a number value. This means you can do calculations.

const number = 5; number > 0; // true Math.sign(number); // 1 

# Solving an Algorithm Challenge with Math.sign

So it allows me to solve this algorithm challenge: «Reverse an Integer»

Input: 123; Output: 321; Input: -123; Output: -321; 
function reverseInteger(num)  const numArray = Math.abs(num) // Get the absolute value of our number > 321 .toString() // Convert our number to a string > '321' .split('') // Convert our string of numbers to an array > [3, 2, 1] .reverse() // Reverse our array of numbers > [1, 2, 3] .join(''); // Convert our array back to a string > 123 const sign = Math.sign(num); // -1 return numArray * sign; // Multiply our reverse string with the sign will produce the correct reverse number > reverseInteger(-321); // -123 

This algorithm question is from Leetcode’s «Reverse an Integer». I edited the requirement of the question to simplify our demonstration. To see the actual solution, here’s one from @loia5tqd001

This is actually when I first discovered this function. That’s why I love looking at other people’s solutions. It’s always interesting to see how other people solve something. Even if the solution is bad, I read those too, cause it teaches me what to avoid πŸ˜‰. No knowledge is wasted πŸ’ͺ. It’s all expanding my toolkit. Just like those learning machines, the more data you feed, the better it gets. I think my brain is like that too. I need to see a lot of solutions in order for me to get better πŸ˜„

That’s why in a lot of my tidbits, I cover the different ways of solving something. Because there is never a BEST function. The best way is always dependant on the situation. The larger your toolkit, the higher chance you will find the best way πŸ‘

# Negative Zero

So you may notice that Math.sign returns a negative zero:

Math.sign(0); // 0 Math.sign(-0); // -0 

And your next question is, what the heck is this negative zero 🀨. Kyle Simpson of «You Don’t Know JS» explains it the best:

Now, why do we need a negative zero, besides academic trivia?

There are certain applications where developers use the magnitude of a value to represent one piece of information (like speed of movement per animation frame) and the sign of that number to represent another piece of information (like the direction of that movement).

In those applications, as one example, if a variable arrives at zero and it loses its sign, then you would lose the information of what direction it was moving in before it arrived at zero. Preserving the sign of the zero prevents potentially unwanted information loss.

# Math.sign Browser Support

Support is great for all modern browsers. Unfortunately, Internet Explorers is too hip to play with the rest of the class. So no support there.

Browser
Chrome βœ…
Firefox βœ…
Safari βœ…
Edge βœ…
Internet Explorer ❌

# Code Tidbit for IE

But no worries, here is an alternative code snippet for you. This will work on Internet Explorer and older browsers πŸ‘

const positive = 5; const negative = -5; const zero = 0; positive === 0 ? positive : positive > 0 ? 1 : -1; // 1 negative === 0 ? negative : negative > 0 ? 1 : -1; // -1 zero === 0 ? zero : zero > 0 ? 1 : -1; // 0 

# Math.sign Polyfill

Or keep using Math.sign and just add this Polyfill from MDN

if (!Math.sign)  Math.sign = function(x)  return (x > 0) - (x  0) || +x; >; > 

# Community Input

: Math.sign() differentiates -0 and +0, this is outputting +0 for both, it is not the same. Anyway Math.sign() is way more readable to me than double ternary, less time to write, less time to read and understand.

Π˜ΡΡ‚ΠΎΡ‡Π½ΠΈΠΊ

Math.sign()

The Math.sign() static method returns 1 or -1, indicating the sign of the number passed as argument. If the input is 0 or -0, it will be returned as-is.

Try it

Syntax

Parameters

Return value

A number representing the sign of x :

  • If x is positive, returns 1 .
  • If x is negative, returns -1 .
  • If x is positive zero, returns 0 .
  • If x is negative zero, returns -0 .
  • Otherwise, returns NaN .

Description

Because sign() is a static method of Math , you always use it as Math.sign() , rather than as a method of a Math object you created ( Math is not a constructor).

Examples

Using Math.sign()

.sign(3); // 1 Math.sign(-3); // -1 Math.sign("-3"); // -1 Math.sign(0); // 0 Math.sign(-0); // -0 Math.sign(NaN); // NaN Math.sign("foo"); // NaN Math.sign(); // NaN 

Specifications

Browser compatibility

BCD tables only load in the browser

See also

Found a content problem with this page?

This page was last modified on Feb 21, 2023 by MDN contributors.

Your blueprint for a better internet.

MDN

Support

Our communities

Developers

Visit Mozilla Corporation’s not-for-profit parent, the Mozilla Foundation.
Portions of this content are Β©1998– 2023 by individual mozilla.org contributors. Content available under a Creative Commons license.

Π˜ΡΡ‚ΠΎΡ‡Π½ΠΈΠΊ

Math

The Math namespace object contains static properties and methods for mathematical constants and functions.

Math works with the Number type. It doesn’t work with BigInt .

Description

Unlike most global objects, Math is not a constructor. You cannot use it with the new operator or invoke the Atomics object as a function. All properties and methods of Math are static.

Note: Many Math functions have a precision that’s implementation-dependent.

This means that different browsers can give a different result. Even the same JavaScript engine on a different OS or architecture can give different results!

Static properties

Euler’s number and the base of natural logarithms; approximately 2.718 .

Natural logarithm of 10 ; approximately 2.303 .

Natural logarithm of 2 ; approximately 0.693 .

Base-10 logarithm of E ; approximately 0.434 .

Base-2 logarithm of E ; approximately 1.443 .

Ratio of a circle’s circumference to its diameter; approximately 3.14159 .

Square root of Β½; approximately 0.707 .

Square root of 2 ; approximately 1.414 .

The initial value of the @@toStringTag property is the string «Math» . This property is used in Object.prototype.toString() .

Static methods

Returns the absolute value of x .

Returns the arccosine of x .

Returns the hyperbolic arccosine of x .

Returns the hyperbolic arcsine of a number.

Returns the arctangent of x .

Returns the arctangent of the quotient of its arguments.

Returns the hyperbolic arctangent of x .

Returns the cube root of x .

Returns the smallest integer greater than or equal to x .

Returns the number of leading zero bits of the 32-bit integer x .

Returns the hyperbolic cosine of x .

Returns e x , where x is the argument, and e is Euler’s number ( 2.718 …, the base of the natural logarithm).

Returns subtracting 1 from exp(x) .

Returns the largest integer less than or equal to x .

Returns the nearest single precision float representation of x .

Returns the square root of the sum of squares of its arguments.

Returns the result of the 32-bit integer multiplication of x and y .

Returns the natural logarithm (㏒e; also, ㏑) of x .

Returns the base-10 logarithm of x .

Returns the natural logarithm (㏒e; also ㏑) of 1 + x for the number x .

Returns the base-2 logarithm of x .

Returns the largest of zero or more numbers.

Returns the smallest of zero or more numbers.

Returns base x to the exponent power y (that is, x y ).

Returns a pseudo-random number between 0 and 1 .

Returns the value of the number x rounded to the nearest integer.

Returns the sign of the x , indicating whether x is positive, negative, or zero.

Returns the hyperbolic sine of x .

Returns the positive square root of x .

Returns the hyperbolic tangent of x .

Returns the integer portion of x , removing any fractional digits.

Examples

Converting between degrees and radians

The trigonometric functions sin() , cos() , tan() , asin() , acos() , atan() , and atan2() expect (and return) angles in radians.

Since humans tend to think in degrees, and some functions (such as CSS transforms) can accept degrees, it is a good idea to keep functions handy that convert between the two:

function degToRad(degrees)  return degrees * (Math.PI / 180); > function radToDeg(rad)  return rad / (Math.PI / 180); > 

Calculating the height of an equilateral triangle

If we want to calculate the height of an equilateral triangle, and we know its side length is 100, we can use the formulae length of the adjacent multiplied by the tangent of the angle is equal to the opposite.

An equilateral triangle where a perpendicular of one edge is drawn from the opposite vertex, forming a right triangle with three sides marked as

In JavaScript, we can do this with the following:

We use our degToRad() function to convert 60 degrees to radians, as Math.tan() expects an input value in radians.

Returning a random integer between two bounds

This can be achieved with a combination of Math.random() and Math.floor() :

function random(min, max)  const num = Math.floor(Math.random() * (max - min + 1)) + min; return num; > random(1, 10); 

Specifications

Browser compatibility

BCD tables only load in the browser

See also

Found a content problem with this page?

This page was last modified on Apr 26, 2023 by MDN contributors.

Your blueprint for a better internet.

MDN

Support

Our communities

Developers

Visit Mozilla Corporation’s not-for-profit parent, the Mozilla Foundation.
Portions of this content are Β©1998– 2023 by individual mozilla.org contributors. Content available under a Creative Commons license.

Π˜ΡΡ‚ΠΎΡ‡Π½ΠΈΠΊ

JavaScript Math.sign()

The Math.sign() method retuns whether a number is negative, positive or zero. If the number is positive, this method returns 1.
If the number is negative, it returns -1.
If the number is zero, it returns 0.

Example 2

Example 3

Browser Support

Math.sign() is an ECMAScript6 (ES6) feature. ES6 (JavaScript 2015) is supported in all modern browsers:

Chrome Edge Firefox Safari Opera
Yes Yes Yes Yes Yes

Math.sign() is not supported in Internet Explorer 11 (or earlier).

Syntax

Parameters

Return Value

  • If the number is positive, it returns 1
  • If the number is negative, it returns -1
  • If the number is positive zero, it returns 0
  • If the number is negative zero, it returns -0
  • If the number is not a number, it returns NaN

Unlock Full Access 50% off

COLOR PICKER

colorpicker

Join our Bootcamp!

Report Error

If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:

Thank You For Helping Us!

Your message has been sent to W3Schools.

Top Tutorials
Top References
Top Examples
Get Certified

W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.

Π˜ΡΡ‚ΠΎΡ‡Π½ΠΈΠΊ

ΠžΡ†Π΅Π½ΠΈΡ‚Π΅ ΡΡ‚Π°Ρ‚ΡŒΡŽ