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?
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.
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.
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.
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.
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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With