Numbers: conversion from scientific notation to bigint

I did some experiments about this.
Did not found anything on MDN.
Tried some stuff from stackoverflow and alike.
Can’t find a way to convert scientific notation to bigint properly.

Results of my attempts are below.
I am using example with 25! for this.

const bigIntFactorial = (n) => {
  let result = BigInt(n);
  let mult = result - BigInt(1);
  while (mult > 0) {
    result *= mult;
    mult--;
  }
  return result;
}

const factorial = (n) => {
  let result = n;
  let mult = result - 1;
  while (mult > 0) {
    result *= mult;
    mult--;
  }
  return result;
}

console.log('factorial with bigint usage')
console.log(bigIntFactorial(25))//15511210043330985984000000n
console.log('factorial without bigint usage')
console.log(factorial(25))//1.5511210043330984e+25
console.log('trying to convert scientific notation to bigint -????')
console.log(BigInt(factorial(25)));//15511210043330983907819520n
console.log('---------');

//trying stuff from web
//console.log(BigInt(factorial(25).toLocaleString()))//syntax error (well, that's a string)

//trying to wrap the above into number
//console.log(BigInt(Number(factorial(25).toLocaleString())))//RangeError: The number NaN cannot be converted to 
//a BigInt because it is not an integer

//trying params for localestring

console.log(BigInt(factorial(25).toLocaleString('fullwide', { useGrouping: false })))

//in the above something happened, some digits missing - ????

If you do not have a big int, then you will lose precision over a certain size of values. You can’t convert reliably ints above the max safe int.

1 Like