Lance Pollard
Lance Pollard

Reputation: 79278

How to Math.floor on BigInt in JavaScript?

Getting this error TypeError: Cannot convert a BigInt value to a number:

function getCompositeNumbers() {
  let v = []
  let i = 1n

  while (i < 1000000n) {
    if (checkIfDivisible(i)) {
      v.push(i)
    }
    i++
  }

  return v
}

function checkIfDivisible(i) {
  if (i/2n == Math.floor(i/2n)) return true
  if (i/3n == Math.floor(i/3n)) return true
  if (i/5n == Math.floor(i/5n)) return true
  if (i/7n == Math.floor(i/7n)) return true
  if (i/11n == Math.floor(i/11n)) return true
  if (i/13n == Math.floor(i/13n)) return true
  return false
}

Upvotes: 5

Views: 7463

Answers (1)

Bergi
Bergi

Reputation: 664620

BigInts are integers, they cannot represent fractional values - it makes no sense to round them. / is integer division, which implicitly truncates decimal digits.

To check for divisibility of BigInts, use

number / divisor * divisor == number
number % divisor == 0n

Upvotes: 11

Related Questions