js print big integer

How to Print a Big Integer in JavaScript?

If you are working with numbers in JavaScript, you may come across a situation where you need to print a big integer. In JavaScript, numbers are represented using the Number data type, which has a maximum value of 2^53 - 1. If you need to work with bigger numbers, you can use libraries like big.js or decimal.js.

Using big.js Library

First, you need to include the big.js library in your HTML file:

<script src="https://cdnjs.cloudflare.com/ajax/libs/big.js/5.2.2/big.min.js"></script>

Then, you can create a new instance of the Big object and pass your big integer as a string:

<div id="output"></div>

<script>
  const bigInt = new Big('12345678901234567890');
  document.getElementById('output').innerHTML = bigInt.toString();
</script>

The output will be:

12345678901234567890

Using decimal.js Library

The decimal.js library works similarly to big.js:

<script src="https://cdnjs.cloudflare.com/ajax/libs/decimal.js/10.2.1/decimal.min.js"></script>

<div id="output"></div>

<script>
  const bigInt = new Decimal('12345678901234567890');
  document.getElementById('output').innerHTML = bigInt.toString();
</script>

The output will be:

12345678901234567890

Using Math.pow() Function

If you don't want to use a library, you can also use the Math.pow() function to calculate the value of a big integer:

<div id="output"></div>

<script>
  const bigInt = Math.pow(10, 20);
  document.getElementById('output').innerHTML = bigInt.toString();
</script>

The output will be:

100000000000000000000

Conclusion

Printing a big integer in JavaScript can be done using libraries like big.js or decimal.js, or by using the Math.pow() function. Depending on your specific use case, one solution may be more appropriate than the others. It's always important to test your code thoroughly to ensure that it works as expected.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe