AnonimousDev123
AnonimousDev123

Reputation: 1

I'm doing a function of inverting values, and the 0, is also inverting, how do I make the 0 not to be negative?

Code in Javascript, please help me to make 0 not negative

function invertSign(val) {

    return (val * -1);
}

console.log(invertSign(1)) -1
console.log(invertSign(-2)) 2
console.log(invertSign(0)) -0

Upvotes: 0

Views: 23

Answers (3)

trincot
trincot

Reputation: 350147

You can use || 0:

function invertSign(val) {
   return -val || 0;
}

If -val evaluates to -0, it will be a falsy value, and so the || operator will evaluate to the second operand, which is 0. And so -0 is replaced by 0.

Alternatively, you subtract from 0:

function invertSign(val) {
   return 0 - val;
}

Here -0 never occurs, because the minus here is not a unary operator, but the binary one. 0 - 0 is just 0, so this may be the simplest solution.

Upvotes: 2

jgpixel
jgpixel

Reputation: 123

Try adding an if statement to check if val === 0.

function invertSign(val) {
    if (val === 0) return val;
    return val * -1;
}

console.log(invertSign(1)); // logs -1
console.log(invertSign(-2)); // logs 2
console.log(invertSign(0)); // logs 0

Upvotes: 0

javascwipt
javascwipt

Reputation: 1178

You can check if the value is zero, and if it is, then return 0


function invertSign(val) {
    if (val === 0) return 0;
    return (val * -1);
}

Upvotes: 0

Related Questions