How to get the first N digits of a BigInteger in TypeScript

1 Answer

0 votes
// Extracts the first n digits from a BigInt.
// Converting the BigInt to a string is the most direct and efficient way
// to access its digits without performing repeated arithmetic operations.
function firstNDigits(value: bigint, n: number): string {
  // Convert the BigInt to its decimal string representation.
  const s: string = value.toString();

  // If n exceeds the number of digits, return the whole number.
  if (n >= s.length) {
    return s;
  }

  // Return the first n characters (digits).
  const result: string = s.slice(0, n);
  
  return result;
}

function main(): void {
  // Define a very large BigInt using the BigInt literal syntax.
  const bigNumber: bigint = 9876543210987654321098765432109876543210n;

  // Choose how many digits to extract.
  const n: number = 19;

  // Extract the first n digits.
  const result: string = firstNDigits(bigNumber, n);

  // Display the result.
  console.log(`First ${n} digits: ${result}`);
}

main();



/*
run:

First 19 digits: 9876543210987654321

*/

 



answered Aug 14 by avibootz
...