UNB/ CS/ David Bremner/ teaching/ cs2613/ books/ mdn/ Reference/ Global Objects/ BigInt/ BigInt.prototype.toString()

The toString() method of BigInt values returns a string representing the specified BigInt value. The trailing "n" is not part of the string.

Syntax

toString()
toString(radix)

Parameters

Return value

A string representing the specified BigInt value.

Exceptions

Description

The BigInt object overrides the toString method of Object; it does not inherit Object.prototype.toString. For BigInt values, the toString() method returns a string representation of the value in the specified radix.

For radixes above 10, the letters of the alphabet indicate digits greater than 9. For example, for hexadecimal numbers (base 16) a through f are used.

If the specified BigInt value is negative, the sign is preserved. This is the case even if the radix is 2; the string returned is the positive binary representation of the BigInt value preceded by a - sign, not the two's complement of the BigInt value.

The toString() method requires its this value to be a BigInt primitive or wrapper object. It throws a TypeError for other this values without attempting to coerce them to BigInt values.

Because BigInt doesn't have a [@@toPrimitive]() method, JavaScript calls the toString() method automatically when a BigInt object is used in a context expecting a string, such as in a template literal. However, BigInt primitive values do not consult the toString() method to be coerced to strings — rather, they are directly converted using the same algorithm as the initial toString() implementation.

BigInt.prototype.toString = () => "Overridden";
console.log(`${1n}`); // "1"
console.log(`${Object(1n)}`); // "Overridden"

Examples

Using toString()

17n.toString(); // "17"
66n.toString(2); // "1000010"
254n.toString(16); // "fe"
(-10n).toString(2); // "-1010"
(-0xffn).toString(2); // "-11111111"

Negative-zero BigInt

There is no negative-zero BigInt as there are no negative zeros in integers. -0.0 is an IEEE floating-point concept that only appears in the JavaScript Number type.

(-0n).toString(); // "0"
BigInt(-0).toString(); // "0"

Specifications

Browser compatibility

See also