6
x = -0
>> -0
typeof(x)
>> "number"
x.toString()
>> "0"
console.log(x)
>> -0

How can I convert Javascript's −0 (number zero with the sign bit set rather than clear) to a two character string ("-0") in the same way that console.log does before displaying it?

user3840170
  • 26,597
  • 4
  • 30
  • 62
Ivan
  • 4,383
  • 36
  • 27

4 Answers4

4

If Node.js (or npm available¹) util.inspect will do that:

> util.inspect(-0)
'-0'

If not, you can make a function:

const numberToString = x =>
    Object.is(x, -0) ?
        '-0' :
        String(x);

Substitute the condition with x === 0 && 1 / x === -Infinity if you don’t have Object.is.

¹ I haven’t read this package’s source and it could be updated in the future anyway; look at it before installing!

Ry-
  • 218,210
  • 55
  • 464
  • 476
2

How about this (idea borrowed from here):

[-0, 0].forEach(function(x){
    console.log(x, x === 0 && 1/x === -Infinity ? "-0" : "0");
});
Salman A
  • 262,204
  • 82
  • 430
  • 521
  • `1 / x === -Infinity` isn’t enough, as it’s true for `x = -1e-309` though `-1e-309 !== 0`. – Ry- Feb 13 '18 at 10:43
0

As per specification, -0 is the only number which Number(String(x)) do not generate the original value of x.

Sadly, all stander toString method tell -0 just like 0. Which convert to string '0' instead of '-0'.

You may be interested in function uneval on Firefox. But since its Firefox only, non-standard feature. You should avoid using it on website. (Also, never do eval(uneval(x)) as deep clone please)

Maybe you have to do this with your own codes:

function numberToString(x) {
  if (1 / x === -Infinity && x === 0) return '-0';
  return '' + x;
}
tsh
  • 4,263
  • 5
  • 28
  • 47
-1

So cant we simply get the sign of -0 it's unique and -0 if sign is -0 we can append '-' to zero.Any thoughts

  • Math.sign(0) and Math.sign(-0) are both 0. The Math.sign() of non-zero numbers are +1 or -1. Maybe you have another way of getting the sign? – Ivan Feb 13 '18 at 12:39
  • 1
    Nope Math.sign(-0) = -0 – Ayeshmantha Perera Feb 14 '18 at 08:08
  • had a look at it again.Check this doc of MSDN also it says Math.sign(-0) = -0 and also Math.sign(+0) = +0 https://learn.microsoft.com/en-us/scripting/javascript/reference/math-sign-function-javascript – Ayeshmantha Perera Feb 14 '18 at 08:09
  • 1
    Okay. The problem is then still the same though: "how to test for -0". 0 and -0 look the same much of the time, for example -0==0 and -0===0. So applying Math.sign() to 0 and -0 doesn't help because it doesn't do anything -- you just get the same out as you put in! – Ivan Feb 14 '18 at 10:22