> "0" console.log(x) >> -0 How can I convert Javascript's −0 (number zero with the sign bit set rathe" /> > "0" console.log(x) >> -0 How can I convert Javascript's −0 (number zero with the sign bit set rathe" /> > "0" console.log(x) >> -0 How can I convert Javascript's −0 (number zero with the sign bit set rathe"/>

How to convert −0 to string with sign preserved?

342 Views Asked by At
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?

4

There are 4 best solutions below

0
Ry- On BEST ANSWER

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!

1
Salman A On

How about this (idea borrowed from here):

[-0, 0].forEach(function(x){
    console.log(x, x === 0 && 1/x === -Infinity ? "-0" : "0");
});
4
tsh On

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;
}
4
Ayeshmantha Perera On

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