Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make number Value opposite in JavaScript

Tags:

javascript

I want to know if it is possible to make a number the opposite to what it currently is using JavaScript. ie if a number is 400. Is it possible to make it -400, similar if a number is -400 is it possible to make it 400?

like image 879
Aaron Lumsden Avatar asked Jul 16 '12 16:07

Aaron Lumsden


People also ask

How do you make a negative number in JavaScript?

To use negative numbers, just place a minus (-) character before the number we want to turn into a negative value: let temperature = -42; What we've seen in this section makes up the bulk of how we will actually use numbers.

How do you get the opposite of a boolean value?

And the "not" ( ! ) operator returns the opposite of the boolean value to its right. That is, true becomes false and false becomes true .


3 Answers

This is not jQuery!

Just multiply it by -1.

num = "400"
console.log(-num);
like image 64
Jay Avatar answered Oct 15 '22 11:10

Jay


Core JS,

function opposite(number) {
  return(-number);
}

As the shorter solution from http://www.codewars.com/

like image 23
InaFK Avatar answered Oct 15 '22 12:10

InaFK


In one Line..

 const opposite = number => -number;
like image 30
Khaled Shehata Avatar answered Oct 15 '22 10:10

Khaled Shehata