Home > Enterprise >  How to convert a BigNumber to a normal number in Typescript
How to convert a BigNumber to a normal number in Typescript

Time:12-29

Guys I am fetching the data from smart contract and it gives a big number in response, I want to convert it into a normal number so that I can use it in order to create a bar chart. How can this be done? enter image description here

This is the piece of code I wrote so that I could store the values in an array:

//Creating candidatevoterarray for graph
    for (var i =0; i<= 4; i  ){
        const temparray = this.candidatearray[i]
        const count = temparray.voteCount
        // this.candidatevotearray.push(count)
        console.log(count)
  }

CodePudding user response:

There is no such thing as a BigNumber in either TypeScript or ECMAScript, nor in Angular. This means that the BigNumber must be something you wrote yourself or coming from some library you are not telling us about.

If it is something you wrote yourself, then only you can know how to convert it to a number or a bigint. If it is something from a library, you will have to look into the documentation of that library.

However, please note that the main reason why someone would write and/or use something like a BigNumber class is because it cannot be represented by number or bigint in the first place! So, it may very well be the case that your BigNumber cannot be converted (accurately) into number or bigint at all.

For example, I just randomly found a library which defines a class / constructor function named BigNumber called bignumber.js. It has a BigNumber.prototype.toNumber method, which converts an instance of BigNumber to an ECMAScript primitive number. But of course, there are infinitely more BigNumbers than there are numbers (more precisely, there are countably infinite BigNumbers but only 264 numbers), so this conversion cannot possibly be accurate. In particular, there is a smallest and a biggest number but there is no smallest or biggest BigNumber, so any BigNumber bigger than the biggest number or smaller than the smallest number cannot be represented at all.

CodePudding user response:

as docs https://docs.ethers.io/v5/api/utils/bignumber/ say there is a method .toNumber() in BigNumber

  • Related