Web3js – Converting Smallest Unit of ERC20 to Full Coins Without Rounding Errors

bignumbererc-20ethereumjtokensweb3js

I can just use web3's fromWei function for all token that have 18 decimal places but I'm not sure how to convert token to full token without having to worry about rounding errors.

For example convert a token with 15 decimals:

convert 12345 to 0.000000000012345 and so on.

Any help is appreciated

Best Answer

Using a library like BigNumber or BN is important in JavaScript to avoid rounding errors in the floating point representation.

Using web3.js:

> web3.toBigNumber(12345).div(10**15).toFixed()
< "0.000000000012345"

Note that when you call a smart contract from JavaScript, you'll typically get a BigNumber object back in the first place, so you can start there (e.g. result.div(10**15).toFixed()).

Related Topic