25

I am using ethers.js I can't figure out how do you convert a bignumber like 1252500000000000000 to 125.25

-Mike

4 Answers 4

33

I was able to use ethers.utils.formatEther( value ) ⇒ string to convert back to readable.

4
  • 4
    Notice that this assumes you are formatting a number with 18 decimals (like eth itself, or most ERC20 tokens). If you wanted to format a token with a different number of decimals (like USDC, which has 6), you need to use ethers.utils.formatUnits(value, 6). formatEther is a shorthand for formatUnits(value, 18). Jun 10, 2021 at 12:53
  • 1
    I have a number that shows as 512 in the etherscan. 0.000000000000000512
    – dcsan
    Oct 31, 2021 at 19:21
  • 1
    current the above returns a tiny number, is there a way to convert a uInt? now i'm doing this: Math.round(parseFloat(str) * (10 ** 18))
    – dcsan
    Oct 31, 2021 at 19:22
  • The key is to keep track the amount of decimal places when working with various tokens, as they might be different and might require different conversion from wei. I had a problem that my approval was for a 18 d.p. number while this ballance indeed didnt exist! May 25, 2022 at 0:58
5
const BigNumber = require('bignumber.js');

let num=new BigNumber(1252500000000000000)
let denom = new BigNumber(10).pow(16)
let ans = num.dividedBy(denom).toNumber()
console.log(ans)

Hope this explains your question.For further info,refer https://mikemcl.github.io/bignumber.js/

2
  • This returns NaN
    – LiveWire
    Jun 5, 2021 at 4:23
  • 1
    I use web3js for above snippet.Sorry i didn't notice etherjs in your question earlier
    – kappa
    Jun 5, 2021 at 7:11
0

parseFloat(value); I have to put in 18 more characters

0

For hexadecimal values you can also directly use ethers.utils.formatEther(_hex)

so if the value is 0x3635c9adc5dea00000 ( equals to 1000 * 18**10 ) you can parse it to ether by directly passing it to formatEther

Your Answer

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

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