Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript. Correctly convert -0 to a string

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?

like image 872
Ivan Avatar asked Feb 13 '18 10:02

Ivan


People also ask

How to convert a number to a string in JavaScript?

How to Convert a Number to a String in JavaScript. There are several built-in methods in JavaScript that convert from an number data type to a String. Let’s discuss each of them. toString()¶ The toString() method takes an integer or floating point number and converts it into a String type. There are two ways of invoking this method.

How to convert a boolean value to a string in JavaScript?

The global method String () can convert booleans to strings. The Boolean method toString () does the same. When JavaScript tries to operate on a "wrong" data type, it will try to convert the value to a "right" type.

How do I convert an object to a string?

The default conversion of objects to string is [object Object]. Notice that there are two object s there, and not just one? And the other is capitalized? Functions, Arrays, Objects, and even Dates and Regex are all objects. And each of them has the toString method.

What is the best way to convert a value to string?

So the battle really comes down to toString () and String () when you want to convert a value to a string. This one does a pretty good job. Except it will throw an error for undefined and null. So definitely be mindful of this As you can see, the String () handles the null and undefined quite well.


1 Answers

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!

like image 92
Ry- Avatar answered Sep 19 '22 13:09

Ry-