Skip to content

Commit

Permalink
util: support BigInt in util.format
Browse files Browse the repository at this point in the history
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'`.
  • Loading branch information
Masashi Hirano committed Sep 16, 2018
1 parent aecfea4 commit 08f67c4
Show file tree
Hide file tree
Showing 3 changed files with 16 additions and 2 deletions.
2 changes: 1 addition & 1 deletion doc/api/util.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
8 changes: 7 additions & 1 deletion lib/util.js
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down
8 changes: 8 additions & 0 deletions test/parallel/test-util-format.js
Original file line number Diff line number Diff line change
Expand Up @@ -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');
Expand Down

0 comments on commit 08f67c4

Please sign in to comment.