Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Semrush - keyword research tool

Create your online store today with Shopify

Turn ChatGPT, Claude, Gemini, And CoPilot Into Your Personal Assistant, Business Coach, Content Creator, And More

AFFILIATE MARKETING Your all-in-one performance engine Manage affiliates, creators, and customer referrals in one unified platform—turning every partnership into measurable growth

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Disclosure: My content contains affiliate links.

43,226 questions

56,128 answers

573 users

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
...