> "0" console.log(x) >> -0 How to convert Javascr...">

Javascript Convert -0 to string correctly

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

How to convert Javascript -0 (a zero number with a sign bit rather than a clean one) to a two-character string ("-0") in the same way as console.log before displaying it?

+4
source share
5 answers

If Node.js (or npm is available ¹) util.inspectdoes this:

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

If not, you can make a function:

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

Replace the condition x === 0 && 1 / x === -Infinityif you do not Object.is.

¹ I have not read this source of packages, and it may be updated in the future; look at it before installation!

+3
source

How about this (idea taken from here ):

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

, -0 - , Number(String(x)) x.

, toString -0 , 0. '0' '-0'.

uneval Firefox. Firefox , . -. ( , eval(uneval(x)) , )

, :

function numberToString(x) {
  if (1 / x === -Infinity && x === 0) return '-0';
  return '' + x;
}
0

, -0, , -0, -0, '-' .

0

, a - +

var a = -0;
var aString= (a==0 && Math.sign(a)==a)? Object.is(-0,a)?"-0":"+0": a.toString();
Console.log(aString);

Give it a try. ES5 introduced “Object.is,” which can distinguish between -0, 0, and +0

-2
source

Source: https://habr.com/ru/post/1693570/


All Articles