25

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

-Mike

Ismael
  • 30,570
  • 21
  • 53
  • 96
LiveWire
  • 763
  • 2
  • 7
  • 9

4 Answers4

33

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

Itération 122442
  • 2,052
  • 1
  • 12
  • 33
LiveWire
  • 763
  • 2
  • 7
  • 9
  • 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). – Franco Victorio Jun 10 '21 at 12:53
  • 1
    I have a number that shows as 512 in the etherscan. 0.000000000000000512 – dcsan Oct 31 '21 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 '21 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! – Konstantin Smirnov May 25 '22 at 00: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/

kappa
  • 171
  • 3
0

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

Adam
  • 101
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

mostafa
  • 101
  • 2