AshKeys

Confessions and Confusions of a Freelance Fullstacker.

Ashok Mannolu Arunachalam, How toJavaScript
Back

How to change the sign of a number in JS

There comes a situation where we need to change a number's sign (+/-). We can do this in two ways:

Math.abs()

abs gives the absolute number irrespective of a number's sign.

js
const randomDiff = Math.abs(Math.random() - Math.random())
console.log(randomDiff)

Math.sign

On the other hand, sign returns the sign of a number as either -1 or 1 or 0 if the number is 0.

js
const randomNumber = Math.random() - Math.random()
const randomDiff = Math.sign(randomNumber) * randomNumber
console.log(randomDiff)