Home > database >  [NodeJS]Converting Exponential to Non Exponential without using any libraries or builtin functions
[NodeJS]Converting Exponential to Non Exponential without using any libraries or builtin functions

Time:11-17

Hello I was just wondering on how to convert an exponential value ex. 1.1111111101111111e 30 to 1111111110111111105345512013824 without the use of any libraries or built in function in NodeJS. need help in understanding how BigInt() converts it. Thank you.

CodePudding user response:

After converting the exponential value number to binary, with Number.toString(2), just read the string as a normal binary integer. The least significant bit is at the end, so we do that in reversed order.

const tobigint = number => {
  const bin = number.toString(2);
  let result = 0n, current = 1n;
  for (let i = bin.length - 1; i >= 0; i--) {
    if (bin[i] == '1') result  = current;
    current *= 2n;
  }
  return number >= 0 ? result : -result;
}

const num = 1.1242241e 30;
console.log(tobigint(num));

  • Related