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

瀏覽器相容性

另見