Skip to content
the poor coder

js print big integer

Poor Man
Published
Reading time
2 min read
On this page

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:

Text
<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:

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

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

The output will be:

Text
12345678901234567890

Using decimal.js Library#

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

Text
<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:

Text
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:

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

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

The output will be:

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

Keep going

2023

how to sort an array

How to Sort an Array If you have an array and you want to order its elements in a specific way, you need to use a sorting algorithm. There are several sorting algorithms available, but two of the most commonly used are…

javascript2 min read
2023

jquery mobile or desktop

jQuery Mobile or Desktop? As a web developer, I have had some experience with both jQuery Mobile and jQuery Desktop. Both frameworks have their pros and cons, and which one to use really depends on the specific project…

javascript1 min read
2023

node.js folder structure

Node.js Folder Structure If you are new to Node.js, it can be daunting to create a folder structure that will work for your project. The structure you choose will depend on the size and complexity of your project. Here…

javascript1 min read
ESC