web3js – How to Convert Wei Value of USDC Balance to Proper Number in Web3.js

web3jswei

I am using this simple code to get wallet balance of USDC. I am not sure how I can convert wei value to proper value. Let's say I have 1,076.235541 USDC in wallet. The below code shows 1076235541 and 0.000000001076235541. But I need to get value 1076 from it.

    const minABI = [
      // balanceOf
      {
        constant: true,
        inputs: [{ name: "_owner", type: "address" }],
        name: "balanceOf",
        outputs: [{ name: "balance", type: "uint256" }],
        type: "function",
      },
    ];
    const tokenAddress = "0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48";
    const walletAddress = MY_WALLET_ADDRESS;

    const contract = new Web3Client.eth.Contract(minABI, tokenAddress);

    async function getBalance() {
      const result = await contract.methods.balanceOf(walletAddress).call();
      const format = Web3Client.utils.fromWei(result); 
      console.log(result);
      console.log(format);
    }

Best Answer

The fromWei function converts from wei to ether, meaning it divides the number by 1e18.

ERC20 tokens allows a custom decimal point precision, USDC specifically uses 6 decimal precision. So you just need to divide your result by 1e6 -

const balance = parseInt(result) / 10**6;

But ideally, to support any ERC20 token, read the number of decimals from the contract and use that; also better use a library that knows how to work with big numbers, because JS has issues when it comes to big/real numbers.

async function getBalance() {
   const result = await contract.methods.balanceOf(walletAddress).call();
   const decimals = await contract.methods.decimals().call();
   const balance = new BigNumber(result).div(10 ** decimals);
   return balance;
}
Related Topic