BigNumbers – Adding BigNumbers with ethers.js

ethers.jsweb3js

I am running tests and use ethers to format big numbers. I can't figure out how to add them.

For example, say I have two numbers I convert into 10 and 100 Finney:

      const x1 = utils.formatUnits("10000000000000000", "finney");
      const x2 = utils.formatUnits("100000000000000000", "finney");

If I console.log them, I see
console.log(x1) generates 10.0, while console.log(x2) generates 100.0. Interestingly,

const y = x2 - x1;

sets y to 90.0, while

const y = x2 + x1;

concatenates the strings, generating 100.010.0.

const y = x2 - - x1;

the above double negative correctly adds, generating 110.0! However, that's an ugly way to get what I want.

"x1.add(x2)", "utils.x1.add(x2)", etc., do not work. Can someone tell me how to add these numbers within my javascript file?

Best Answer

On ethers V5 the output is usually a object with two fields, isBignumber (boolean) and _hex field with a string representing the hexadecimal value of that number. So you need to pass inside Number(bigNumber._hex) in orther to make math. Ethers V6 would returning straight a BigInt(), big integers can do math with eachother but if you try to perform math between a big integer and a regular number it will also complain. Again you need to pass it inside Number().

Related Topic