1

Is there any function in go-ethereum, which can convert values from ether to wei and vice-versa?

I should notice, that I'm not using geth as standalone app, I'm using go-ethereum as imported libraries to my golang app, so using console is not an option

I want to ask if go-etherum has some converter function inside it, or, probably, someone know other non-official library at go, which can convert Ethereum values.

2 Answers 2

1

Go-ethereum exposes the web3 API:

https://geth.ethereum.org/docs/interface/javascript-console

So, if amt is in ETH, you can do:

web3.utils.toWei(amt,'ether')

and

web3.utils.fromWei(amt, 'ether')

See:

https://web3js.readthedocs.io/en/v1.2.6/web3-utils.html#towei

4
  • Ok, I should add that I'm not using geth as standalone app, I'm using go-ethereum modules as imported libraries to my golang app (for interaction with smart-contracts, transaction, event's, etc) Therefore I cannot use java-script console So, Im asking -- is there anything inside go-ethereum for making such conversions? Or probably you know any other go-lib for doing so? Commented Jun 15, 2020 at 13:38
  • @JackBekket I'm not sure of the arithmetic precision in go, but could you just divide or multiply by 1000000000000000000? I don't know re. the go-ethereum internals. Why not update your question with this context?
    – Lee
    Commented Jun 15, 2020 at 14:18
  • Yes, currently the only solution is to do amt*10^18, but it feels unsafety and not really convinient as such simple functions from web3 :c Also, probably you know, why there are no implementation of web3 in go? Commented Jun 15, 2020 at 18:39
  • @JackBekket I don't know, and I also don't know why there'd need to be one either.
    – Lee
    Commented Jun 19, 2020 at 13:10
0

Float*10^18 will overflow fairly quickly. I am using the following function:

func FloatTo18z(amount float64) *big.Int {
    s := fmt.Sprintf("%f", amount)
    a := strings.Split(s, ".")
    for i := 0; i < 18; i++ {
        if len(a) > 1 && len(a[1]) > i {
            a[0] += string(a[1][i])
        } else {
            a[0] += "0"
        }
    }
    b, ok := new(big.Int).SetString(a[0], 10)
    if !ok {
        panic("Could not set big.Int string for value " + s)
    }
    return b
}

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.