Search code examples
javascriptnegative-zero

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?


Solution

  • 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!