Skip to content

Commit

Permalink
util: Format negative zero as '-0'
Browse files Browse the repository at this point in the history
Format negative zero as '-0' instead of as '0', as it does not behave
identically to positive zero. ((-0).toString() still returns '0' as
required by ES5 9.8.1.2).

Fixes nodejs/node-v0.x-archive#6548.
Closes nodejs/node-v0.x-archive#6550.
  • Loading branch information
David Chan authored and TooTallNate committed Nov 25, 2013
1 parent de8c0a5 commit b3e4fc6
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 1 deletion.
7 changes: 6 additions & 1 deletion lib/util.js
Original file line number Diff line number Diff line change
Expand Up @@ -323,8 +323,13 @@ function formatPrimitive(ctx, value) {
.replace(/\\"/g, '"') + '\'';
return ctx.stylize(simple, 'string');
}
if (isNumber(value))
if (isNumber(value)) {
// Format -0 as '-0'. Strict equality won't distinguish 0 from -0,
// so instead we use the fact that 1 / -0 < 0 whereas 1 / 0 > 0 .
if (value === 0 && 1 / value < 0)
return ctx.stylize('-0', 'number');
return ctx.stylize('' + value, 'number');
}
if (isBoolean(value))
return ctx.stylize('' + value, 'boolean');
// For some reason typeof null is "object", so special case here.
Expand Down
4 changes: 4 additions & 0 deletions test/simple/test-util-inspect.js
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,10 @@ Date2.prototype.foo = 'bar';
var after = util.inspect(d);
assert.equal(orig, after);

// test positive/negative zero
assert.equal(util.inspect(0), '0');
assert.equal(util.inspect(-0), '-0');

// test for sparse array
var a = ['foo', 'bar', 'baz'];
assert.equal(util.inspect(a), '[ \'foo\', \'bar\', \'baz\' ]');
Expand Down

0 comments on commit b3e4fc6

Please sign in to comment.