Search code examples
flutterdartmetamask

Is it possible to get the balance without the decimals or a specific amount of decimals?


I am using the web3 package and I am getting the balance like so

final abi = [
  'function balanceOf(address) view returns (uint)',
];

final token = web3.Contract(
  '{contract address}',
  abi,
  web3.provider!,
);

final balance = await token.call<BigInt>(
  'balanceOf',
  ['{walletAddress}'],
);

print('BALANCE: ${balance}');

But when I print the balance I notice it also has the decimals. How can I get the balance without the decimals? Or with a specific amount of decimals? Or read what amount of decimals have been set on the token details?

My balance is 999987 and I get 999987000000000000000000


Solution

  • As James suggested there is a decimals function

    const abi = [
      'function balanceOf(address) view returns (uint)',
      'function decimals() view returns (uint)',
    ];
    
    final token = web3.Contract(
      contractAddress,
      abi,
      web3.provider!,
    );
    
    final balance = await token.call<BigInt>(
      'decimals',
      [],
    );