JS: BigInt converter function

By Xah Lee. Date: .

Convert string to bigint

// string to bigint
const xbig1 = BigInt("123456789012345678901234567890");
console.log(xbig1);
// 123456789012345678901234567890n

console.log(Number.MAX_SAFE_INTEGER);
// 9007199254740991

Convert hexadecimal string to bigint

// hexadecimal to bigint

const xbig1 = BigInt("0xFF");
console.log(xbig1);
// 255n

Convert number to bigint

// number to bigint. the number must be less than Number.MAX_SAFE_INTEGER
const xbig2 = BigInt(123);
console.log( xbig2 )
// 123n

🛑 WARNING: Passing a standard Number type with more than 15 digits to BigInt() does not work, because the number is coerced to a Number first.

Cannot be used with new

🛑 WARNING: cannot be called with new.

new BigInt("123")
// error: Uncaught (in promise) TypeError: BigInt is not a constructor

Do not accept float

🛑 WARNING: You cannot pass a floating number or a string with decimals to BigInt().

BigInt(1.5)
// error: Uncaught (in promise) RangeError: The number 1.5 cannot be converted to a BigInt because it is not an integer
BigInt("1.5")
// error: Uncaught (in promise) SyntaxError: Cannot convert 1.5 to a BigInt

JavaScript bigint