0

How can I use moneyphp/money to get the money in dollars from cents?

I am storing price as cents in my database, and lets say I have this accessor in a laravel model

    public function getPriceAttribute($price)
    {
        $fiver = Money::USD(1425);
        dd($fiver->getAmount());
    }

the getAmount method will show 1425 while I am expecting 14.25

Community
  • 1
  • 1
rook99
  • 1,034
  • 10
  • 34

1 Answers1

2

MoneyPHP internally stores the amount in cents as a string. The getAmount method simply returns the internally stored amount.

To get a formatted amount from MoneyPHP you should use a formatter.

<?php
use Money\Currencies\ISOCurrencies;
use Money\Currency;
use Money\Formatter\IntlMoneyFormatter;
use Money\Money;

$money = new Money(1425, new Currency('USD'));
$currencies = new ISOCurrencies();

$numberFormatter = new \NumberFormatter('en_US', NumberFormatter::DECIMAL);
$moneyFormatter = new IntlMoneyFormatter($numberFormatter, $currencies);

echo $moneyFormatter->format($money); // outputs 14.25

If you also need the currency symbol replace NumberFormatter::DECIMAL with NumberFormatter::CURRENCY.