11

I am trying to generate a 20 digit random number:

let code = Math.floor(10000000000000000000n + Math.random() * 90000000000000000000n)

I have tried putting the numbers in BigInt() as well as adding a n after but still this error comes.

Uncaught TypeError: Cannot mix BigInt and other types, use explicit conversions
Manan Sharma
  • 507
  • 1
  • 5
  • 18

1 Answers1

10
// An operation with a fractional result will be truncated when used with a BigInt.

const rounded = 5n / 2n
// ↪ 2n, not 2.5n

// BigInt value can only operator with same type

// random BigInt
BigInt(Math.floor(Math.random() * 10))

// generate a 20 digit random number
BigInt(Math.floor(Math.random() * 100000000000000000000))

you can check this

Liu Lei
  • 1,256
  • 1
  • 9
  • 18
  • Hey, but I do need that `Math.random()` function since I'm trying to return a random 20 digit value. The truncating is not a problem though. – Manan Sharma Aug 26 '20 at 06:43