How to convert −0 to string with sign preserved?
Asked Answered
T

4

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?

Teaspoon answered 13/2, 2018 at 10:30 Comment(1)
Is this Node.js or no? What kind of compatibility do you need?Buchan
B
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!

Buchan answered 13/2, 2018 at 10:30 Comment(0)
B
2

How about this (idea borrowed from here):

[-0, 0].forEach(function(x){
    console.log(x, x === 0 && 1/x === -Infinity ? "-0" : "0");
});
Breeze answered 13/2, 2018 at 10:36 Comment(1)
1 / x === -Infinity isn’t enough, as it’s true for x = -1e-309 though -1e-309 !== 0.Buchan
B
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;
}
Bolte answered 13/2, 2018 at 10:42 Comment(4)
1 / x === -Infinity isn’t enough, as it’s true for x = -1e-309 though -1e-309 !== 0.Buchan
I just wrote up your comment as an answer, but as you have done the same, I just removed mine. Thanks for uneval.Teaspoon
@user3070485: … you needed it in Firefox/js* only?Buchan
@Ryan ok, fixed.Bolte
S
-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

Staccato answered 13/2, 2018 at 11:18 Comment(4)
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?Teaspoon
Nope Math.sign(-0) = -0Staccato
had a look at it again.Check this doc of MSDN also it says Math.sign(-0) = -0 and also Math.sign(+0) = +0 learn.microsoft.com/en-us/scripting/javascript/reference/…Staccato
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!Teaspoon

© 2022 - 2024 — McMap. All rights reserved.