Ivan
Ivan

Reputation: 4753

How to convert −0 to string with sign preserved?

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?

Upvotes: 6

Views: 484

Answers (4)

Ayeshmantha Perera
Ayeshmantha Perera

Reputation: 909

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

Upvotes: -1

Salman Arshad
Salman Arshad

Reputation: 272096

How about this (idea borrowed from here):

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

Upvotes: 2

tsh
tsh

Reputation: 4738

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;
}

Upvotes: 0

Ry-
Ry-

Reputation: 224905

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!

Upvotes: 4

Related Questions