4

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

xeraphim
  • 4,375
  • 9
  • 54
  • 102
  • Your function works for me, php7.1 and bc-math installed. What is your function call and what is on line 121? – Michel Aug 06 '17 at 07:12
  • Strange oO My PHP Version is Apache Version Apache/2.4.26 (Win32) OpenSSL/1.0.2l PHP/7.1.7 and bc-math should be enabled too... `BCMath support enabled`. Line 121 is: `return bcdiv($wei,1000000000000000000,18);` and the function call is like this: $eth = wei2eth(getETHBalance($ethwallet)); where getETHBalance is 9357929650000000000 – xeraphim Aug 06 '17 at 09:01

2 Answers2

10

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.

Michel
  • 950
  • 14
  • 23
0

I use this function:

function cryptoNumberFormat($value, $decimal){
    $dividend = (string)$value;
    $divisor = (string)'1'. str_repeat('0', $decimal);
    return bcdiv($value, $divisor, $decimal);
}

You can format any crypto token with any decimal precision and value. No need to provide the values as strings.

Cagy79
  • 1,610
  • 1
  • 19
  • 25