Skip to content

Commit b3e4fc6

Browse files
David ChanTooTallNate
David Chan
authored andcommitted
util: Format negative zero as '-0'
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.
1 parent de8c0a5 commit b3e4fc6

File tree

2 files changed

+10
-1
lines changed

2 files changed

+10
-1
lines changed

lib/util.js

+6-1
Original file line numberDiff line numberDiff line change
@@ -323,8 +323,13 @@ function formatPrimitive(ctx, value) {
323323
.replace(/\\"/g, '"') + '\'';
324324
return ctx.stylize(simple, 'string');
325325
}
326-
if (isNumber(value))
326+
if (isNumber(value)) {
327+
// Format -0 as '-0'. Strict equality won't distinguish 0 from -0,
328+
// so instead we use the fact that 1 / -0 < 0 whereas 1 / 0 > 0 .
329+
if (value === 0 && 1 / value < 0)
330+
return ctx.stylize('-0', 'number');
327331
return ctx.stylize('' + value, 'number');
332+
}
328333
if (isBoolean(value))
329334
return ctx.stylize('' + value, 'boolean');
330335
// For some reason typeof null is "object", so special case here.

test/simple/test-util-inspect.js

+4
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,10 @@ Date2.prototype.foo = 'bar';
3434
var after = util.inspect(d);
3535
assert.equal(orig, after);
3636

37+
// test positive/negative zero
38+
assert.equal(util.inspect(0), '0');
39+
assert.equal(util.inspect(-0), '-0');
40+
3741
// test for sparse array
3842
var a = ['foo', 'bar', 'baz'];
3943
assert.equal(util.inspect(a), '[ \'foo\', \'bar\', \'baz\' ]');

0 commit comments

Comments
 (0)