How to convert BigNumber to Number in Truffle framework?

Lucas: 2 weeks ago

I have written an ERC20 token contract and deployed it in test network using truffle framework. When I check the token balance for an account using web3 it was giving the result in BigNumber when I try to convert it to a number using toNumber() getting an unexpected result.

Solidity code:

  function balanceOf(address _from) constant public returns (uint256 balance) {
    return balances[_from];

Javascript code:

instantiateBalance() {
const contract = require('truffle-contract')
const token = contract(Token)
var tokenInstance;
token.deployed().then(function(instance) {
tokenInstance = instance;
return"0xb1Cf866ced575FD1A1997Daa5d6F099efb282E41", {from: "0xb1Cf866ced575FD1A1997Daa5d6F099efb282E41"});
}).then(function(balance) {

Expected Result

Decimals = 18

Actual Token Balance = 100000000.000000000000000000

Actual Result

Token Balance = 1000000000000


Mia: 2 weeks ago

If your token have 18 decimals

like an ether you can use

then(function(balance) {
    console.log(web3.fromWei(balance.toNumber(), "ether" ) );

Use fromWei ( to convert your bigNumber to ether and then convert it to Number. Be aware that unnecessary 0 after the floating point will not be displayed.

In web3 ^1.0 it may change to web3.utils.fromWei instead of web3.fromWei doc ( Note that truffle ^5.0 uses web3 ^1.0.

If you have a different token decimal

Let's say 6. You'll have to do the conversion manually with something like:

var tokenBalance = balance.ToNumber() / Math.pow(10, tokenDecimals)