From b3e4fc6a48b97b52bd19de43c76b7082dcab4988 Mon Sep 17 00:00:00 2001 From: David Chan Date: Wed, 20 Nov 2013 23:40:41 +0530 Subject: [PATCH] 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 joyent/node#6548. Closes joyent/node#6550. --- lib/util.js | 7 ++++++- test/simple/test-util-inspect.js | 4 ++++ 2 files changed, 10 insertions(+), 1 deletion(-) diff --git a/lib/util.js b/lib/util.js index b0bbdd4ae9f7a7..a03e87449c873b 100644 --- a/lib/util.js +++ b/lib/util.js @@ -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. diff --git a/test/simple/test-util-inspect.js b/test/simple/test-util-inspect.js index 132726b1bcbf2a..86eceea93233bd 100644 --- a/test/simple/test-util-inspect.js +++ b/test/simple/test-util-inspect.js @@ -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\' ]');