1

I need to define a sign function which returns either -1 or 1. The Math.sign function does not suffices since it returns -0 and0 respectively for the inputs -0 and 0.

My first attempt at solving this was...

function my_sign(a) {
    let sign = Math.sign(a);
    if (sign === 0 || sign === 1){
        return 1;
    } else {
        return -1;
    }
}

Although, since 0 === -0 is true, this does not work. How to proceed?

Olivier Melançon
  • 21,584
  • 4
  • 41
  • 73
  • I'm not sure how JS stores `-0` but `console.log(-0);`is `0`. – Sascha Sep 03 '20 at 19:31
  • The idea in the dulicate works... but it's in Java. Isn't there a better approach in JS? – Olivier Melançon Sep 03 '20 at 19:37
  • It works in JS too https://jsfiddle.net/7p8wt4km/5/ For more background-information look https://medium.com/coding-at-dawn/is-negative-zero-0-a-number-in-javascript-c62739f80114 – Sascha Sep 03 '20 at 19:38
  • @Sascha By the way, I believe not all machines permit a -0. Might be why you don't have one. The duplicate does work, so I will proceed with that. But it feels weird there isn't a copySign function or something similar. – Olivier Melançon Sep 03 '20 at 19:41

0 Answers0