2

So I'm trying to convert Ethereum Wei to Eth. The described method of doing this is to divide by 10^18. However my attempt to do this is not producing the right values.

private static Decimal toEth(String wei) {
    System.debug(wei);
    Decimal ethAmount = Decimal.valueOf(wei).divide(10^18, 2, System.RoundingMode.UP);
    System.debug(ethAmount);
    return ethAmount;
}

I was hoping that someone might know off the top of their head why this isn't working.

17:24:02.30 (340307342)|USER_DEBUG|[4]|DEBUG|1000000000000000000
17:24:02.30 (340773708)|USER_DEBUG|[6]|DEBUG|41666666666666666.67
17:24:02.30 (340859619)|USER_DEBUG|[4]|DEBUG|50000000000
17:24:02.30 (340918639)|USER_DEBUG|[6]|DEBUG|2083333333.34
17:24:02.30 (341742530)|USER_DEBUG|[4]|DEBUG|998866000000000000
17:24:02.30 (341821603)|USER_DEBUG|[6]|DEBUG|41619416666666666.67
17:24:02.30 (341852276)|USER_DEBUG|[4]|DEBUG|54000000000
17:24:02.30 (341895487)|USER_DEBUG|[6]|DEBUG|2250000000.00
17:24:02.30 (342353811)|USER_DEBUG|[4]|DEBUG|400001000000000000000000
17:24:02.30 (342540215)|USER_DEBUG|[6]|DEBUG|16666708333333333333333.34
17:24:02.30 (342613123)|USER_DEBUG|[4]|DEBUG|54000000000
17:24:02.30 (342682201)|USER_DEBUG|[6]|DEBUG|2250000000.00
17:24:02.30 (343232044)|USER_DEBUG|[4]|DEBUG|1000000000000000
17:24:02.30 (343293233)|USER_DEBUG|[6]|DEBUG|41666666666666.67
17:24:02.30 (343323784)|USER_DEBUG|[4]|DEBUG|31824000000
17:24:02.30 (343365219)|USER_DEBUG|[6]|DEBUG|1326000000.00
17:24:02.30 (343715745)|USER_DEBUG|[4]|DEBUG|1999000000000000000
17:24:02.30 (343772847)|USER_DEBUG|[6]|DEBUG|83291666666666666.67
17:24:02.30 (343801964)|USER_DEBUG|[4]|DEBUG|45000000000
17:24:02.30 (343841403)|USER_DEBUG|[6]|DEBUG|1875000000.00
1
  • 2
    (to post preformatted text, wrap in triple backticks: ```)
    – David Reed
    Jun 18 '20 at 0:36
4

^ is not an exponentiation operator in Apex. It is bitwise XOR.

10^18 actually evaluates to 24, which makes sense of your division results.

To perform exponentiation, use Math.pow(), e.g.

Math.pow(10, 18)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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