BigInt.prototype.toString()

Baseline 已广泛支持

此功能已成熟,并可在许多设备和浏览器版本上使用。自 2020 年 9 月起,所有浏览器均已提供此功能。

toString() 方法是 BigInt 值的一个方法,用于返回一个表示指定 BigInt 值的字符串。末尾的 "n" 不是字符串的一部分。

试一试

console.log(1024n.toString());
// Expected output: "1024"

console.log(1024n.toString(2));
// Expected output: "10000000000"

console.log(1024n.toString(16));
// Expected output: "400"

语法

js
toString()
toString(radix)

参数

radix 可选

一个 2 到 36 之间的整数,指定用于表示 BigInt 值的进制。默认为 10。

返回值

一个表示指定 BigInt 值的字符串。

异常

RangeError

如果 radix 小于 2 或大于 36,则抛出此错误。

描述

BigInt 对象覆盖了 ObjecttoString 方法;它不继承 Object.prototype.toString()。对于 BigInt 值,toString() 方法返回该值在指定进制下的字符串表示。

对于大于 10 的进制,字母用于表示大于 9 的数字。例如,对于十六进制数(进制 16),会使用 af

如果指定的 BigInt 值是负数,则会保留符号。即使进制为 2,也是如此;返回的字符串是 BigInt 值的正二进制表示,前面加上一个 - 符号,而不是 BigInt 值的二进制补码。

toString() 方法要求其 this 值是一个 BigInt 原始值或包装对象。对于其他 this 值,它会抛出 TypeError,而不会尝试将其强制转换为 BigInt 值。

由于 BigInt 没有 [Symbol.toPrimitive]() 方法,当 BigInt 对象在需要字符串的上下文(如 模板字面量)中使用时,JavaScript 会自动调用 toString() 方法。但是,BigInt 原始值强制转换为字符串时,并不会查询 toString() 方法——而是直接使用与初始 toString() 实现相同的算法进行转换。

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

示例

使用 toString()

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

负零 BigInt

不存在负零 BigInt,因为整数中不存在负零。-0.0 是 IEEE 浮点数概念,仅出现在 JavaScript 的 Number 类型中。

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

规范

规范
ECMAScript® 2026 语言规范
# sec-bigint.prototype.tostring

浏览器兼容性

另见