0

I am pulling data from a feed and storing this as a string. In this data I have a price in ETH which looks like this:

string(12) "9.9121566185"

I want to convert this number to WEI and store it as a Money/Php object

When I try the following:

$money = new Money('9.9121566185', new Currency('ETH'));
echo $money->getAmount();

I get the error:

Amount must be an integer(ish) value

So I am thinking I need to do the following:

  1. Convert the string from ETH to WEI as an integer or 9912156618500000000
  2. As the number is big, I should use moontoast/math
  3. Once converted, I can store the new number as WEI in the Money object
  4. Go on holiday!

I am stuck on how to convert the ETH string value to a WEI value...

BenMorel
  • 34,448
  • 50
  • 182
  • 322
HappyCoder
  • 5,985
  • 6
  • 42
  • 73
  • Possible duplicate of [PHP String to Float](https://stackoverflow.com/questions/481466/php-string-to-float) – rollstuhlfahrer Feb 07 '18 at 13:11
  • 1
    Not a duplicate, the floatVal solution is not satisfactory. – HappyCoder Feb 07 '18 at 18:02
  • You can also use [brick/math](https://github.com/brick/math) to convert big numbers (it works with and without BCMath and GMP). If you're not locked with moneyphp/money, you can also use [brick/money](https://github.com/brick/money) which is based on brick/math and natively handles large numbers and custom currencies. – BenMorel Feb 08 '18 at 16:54

2 Answers2

0

As I am dealing with currency, something like floatVal is not going to work because a remainder or anything other than the expected value adds up over time.

So this is how I have solved the issue:

  1. Get the ETH string value: string(12) "9.9121566185"
  2. $bn = new \Moontoast\Math\BigNumber('9.9121566185',17); //Adds 17 decimal places
  3. $bn->multiply(1000000000000000000); //multiplies out by 1.0 E+18
  4. $bn2 = new \Moontoast\Math\BigNumber($bn->getValue(),0); //Chops off the remainder
  5. $wei = $bn2->getValue();

The above outputs exactly:

string(19) "9912156618500000000"
HappyCoder
  • 5,985
  • 6
  • 42
  • 73
0

you should use parser to turn the number to money object

$currencies = [
 'ETH' => 18
];
$currencyList = \Money\Currencies\CurrencyList($currencies);
$parser = new \Money\Parser\DecimalMoneyParser($currencyList);
$ethMoney =$parser->parse('9.9121566185', new \Money\Currency('ETH'));