Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert Wei to Ethereum with php

I'm trying to convert wei to eth by using php and the bc-math extension.

when trying to convert it using this function:

function wei2eth($wei)
{
    return bcdiv($wei,1000000000000000000,18);
}

I get the following error:

Warning: bcdiv(): Division by zero in C:\xampp\htdocs\test\coindata.php on line 121

Has anyone used the bc-math extension and bcdiv to convert wei to eth and knows, why I get this error?

Thanks in advance

like image 338
xeraphim Avatar asked Sep 14 '25 07:09

xeraphim


1 Answers

Your inputs needs to be specified as a string with bc-math, specially with the input greater than PHP_INT_MAX. The signature of bcdiv is as follow:

string bcdiv ( string $left_operand , string $right_operand [, int $scale = 0 ] )

On my 64bit machine, your function works until $wei >= PHP_INT_MAX (9223372036854775807 in my case) because PHP cast the input properly until then.

echo wei2eth('9357929650000000000');
// output 9.357929650000000000

echo wei2eth(9357929650000000000);  // 
// output 0.000000000000000000 and no warning with my env.

Also you need to modify the second argument of bcdiv too:

function wei2eth($wei)
{
    return bcdiv($wei,'1000000000000000000',18);
}

because I suspect that your system is 32bit and your second argument is cast to '0', hence the division by zero error.

like image 121
Michel Avatar answered Sep 15 '25 21:09

Michel