Skip to content

How can I convert Wei to Ethereum with PHP?

A poster with the words "how can i convert wei to ethereum to php?'

In PHP, you can convert Wei to Ethereum using the bcmath extension, which provides support for arbitrary precision math.

What’s bcmath?

The bcmath extension is a PHP extension that provides a set of functions that allow developers to perform mathematical operations with arbitrary precision, which is useful when working with large numbers or decimal numbers that require a high degree of accuracy.

The bcmath functions use strings to represent numbers, allowing them to handle numbers with an arbitrary number of digits. This makes them useful for tasks such as financial calculations, cryptography, and other applications that require precise calculations.

Some of the commonly used functions in bcmath

  1. bcadd() : adds two arbitrary precision numbers
  2. bcsub() : subtracts one arbitrary precision number from another
  3. bcmul() : multiplies two arbitrary precision numbers
  4. bcdiv() : divides one arbitrary precision number by another
  5. bcmod() : computes the modulus of an arbitrary precision number
  6. bcpow() : raises an arbitrary precision number to a power
  7. bcsqrt() : computes the square root of an arbitrary precision number
  8. bcscale() : sets the default scale used by all bcmath functions

General steps to convert Wei to Ethereum with PHP bcmath extension

1. Make sure the bcmath extension is enabled on your PHP installation

The bcmath extension is not enabled by default in PHP, so you will need to check the output of phpinfo() or by adding extension=bcmath.so in your php.ini file to check if the extension is enabled, and if not, you’ll need to enable it before using these functions in your code.

2. Use the bcdiv() function to divide the Wei value by 10^18, since there are 10^18 Wei in 1 Ether.

For example:

$wei = "1000000000000000000";
$ether = bcdiv($wei, "1000000000000000000", 18);

Note that the third parameter “18” is the precision, the amount of decimal places the result will have.

3. You can also use the bcmul() function to multiply the ether value to convert back to wei

$wei = bcmul($ether, "1000000000000000000",0);

Here the last parameter “0” is to round off the resultant value to zero decimal places.

A practical example in your code would look like this:

<?php
    $wei = "1000000000000000000";
    $ether = bcdiv($wei, "1000000000000000000", 18);
    echo $ether;
    $wei = bcmul($ether, "1000000000000000000",0);
    echo $wei;
?>

It would output “1” and “1000000000000000000” respectively

Please note that as Ethereum uses floating point numbers and the bcmath uses decimal numbers, in some cases it might not be precise for very high numbers or for very low precision.