From 08f67c4e87d7a2ad32fc3e4038f57e2699ef0e8d Mon Sep 17 00:00:00 2001 From: Masashi Hirano Date: Fri, 3 Aug 2018 00:52:27 +0900 Subject: [PATCH] util: support BigInt in util.format Adding support for BigInt in util.format and console.log. Placeholder `%d` is replaced as Number when BigInt is set in second argument. Now, `util.format('%d', 1180591620717411303424n)` returns `'1.1805916207174113e+21'`. However, expected result is `'1180591620717411303424'`. --- doc/api/util.md | 2 +- lib/util.js | 8 +++++++- test/parallel/test-util-format.js | 8 ++++++++ 3 files changed, 16 insertions(+), 2 deletions(-) diff --git a/doc/api/util.md b/doc/api/util.md index d29fbfc5b7f050..96838fb8e2f77c 100644 --- a/doc/api/util.md +++ b/doc/api/util.md @@ -198,7 +198,7 @@ Each placeholder token is replaced with the converted value from the corresponding argument. Supported placeholders are: * `%s` - `String`. -* `%d` - `Number` (integer or floating point value). +* `%d` - `Number` (integer or floating point value) or `BigInt`. * `%i` - Integer. * `%f` - Floating point value. * `%j` - JSON. Replaced with the string `'[Circular]'` if the argument diff --git a/lib/util.js b/lib/util.js index 89c86cb7fd0050..24b7a931396aac 100644 --- a/lib/util.js +++ b/lib/util.js @@ -291,7 +291,13 @@ function formatWithOptions(inspectOptions, f) { tempStr = tryStringify(arguments[a++]); break; case 100: // 'd' - tempStr = `${Number(arguments[a++])}`; + const tempNum = arguments[a++]; + // eslint-disable-next-line valid-typeof + if (typeof tempNum === 'bigint') { + tempStr = `${tempNum}n`; + } else { + tempStr = `${Number(tempNum)}`; + } break; case 79: // 'O' tempStr = inspect(arguments[a++], inspectOptions); diff --git a/test/parallel/test-util-format.js b/test/parallel/test-util-format.js index a8adf936719932..5a85870f1a33c0 100644 --- a/test/parallel/test-util-format.js +++ b/test/parallel/test-util-format.js @@ -68,6 +68,14 @@ assert.strictEqual(util.format('%d', -0.5), '-0.5'); assert.strictEqual(util.format('%d', ''), '0'); assert.strictEqual(util.format('%d %d', 42, 43), '42 43'); assert.strictEqual(util.format('%d %d', 42), '42 %d'); +assert.strictEqual( + util.format('%d', 1180591620717411303424), + '1.1805916207174113e+21' +); +assert.strictEqual( + util.format('%d', 1180591620717411303424n), + '1180591620717411303424n' +); // Integer format specifier assert.strictEqual(util.format('%i'), '%i');