1

I want to convert bigNumber to Ether unit. I used the formatEther keyword but I keep getting "Typeerror: formatEther is not a function.

Here's the code:

const axios = require("axios");
const BigNumber = require("bignumber.js");
const formatEther = require("ethers");

// copy-paste your URL provided in your Alchemy.com dashboard
const ALCHEMY_URL =
  "......";

axios
  .post(ALCHEMY_URL, {
    jsonrpc: "2.0",
    id: 1,
    method: "eth_getBalance",
    params: [
      "0xC..................", // Ethereum address
      "latest", // get latest account balance of the address
    ],
  })
  .then((response) => {
    const result = BigNumber(response.data.result);
    const numberString = formatEther(result);
    console.log(numberString);
  });
2
  • 1
    never share any API keys publicly on the internet. yours is included in your code snippet .. even if you just use it for testing or whatever, better keep secrets secret.
    – timsntech
    Feb 13 at 12:20
  • Hey, I see that documentation has changed, try destructuring formatEther. const {formatEther} = require('ethers');
    – vampireAb
    Feb 13 at 17:12

2 Answers 2

1

Have a look at the code below, you can use ethers.utils.formatEther and also ethers.BigNumber.from from ethers utils. This should do the job.

const axios = require("axios");
const { ethers } = require("ethers");

const ALCHEMY_URL = "YOUR_ALCHEMY_API_URL";

axios
  .post(ALCHEMY_URL, {
    jsonrpc: "2.0",
    id: 1,
    method: "eth_getBalance",
    params: [
      "0xC..................", // Ethereum address
      "latest", // get latest account balance of the address
    ],
  })
  .then((response) => {
    const result = ethers.BigNumber.from(response.data.result);
    const numberString = ethers.utils.formatEther(result);
    console.log(numberString);
  });

If you want to further destructure your imports you can do:

const { utils, BigNumber } = require("ethers");

and use it as follows:

const result = BigNumber.from(response.data.result);
const numberString = utils.formatEther(result);
3
  • Thanks but I'm getting this error: UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'from' of undefined
    – Ololade
    Feb 13 at 16:23
  • what version of ethers are you using? check your package.json. The cannot read ... from undefined is an error couple of people have in beta version ethers@6.x, downgrade to ethers@5.7.2 and reinstall packages, should work!
    – timsntech
    Feb 13 at 16:33
  • You're the best. It worked. I'd love to learn more from you - if you're open to it. Thanks.
    – Ololade
    Feb 14 at 8:15
0

It still works, it's included in utils, check here

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.