PHP Function money_format()

I hope everyone had a great Thanksgiving! 🙂

I was inspired for this week’s Function Friday when I was working with Stripe API (using PHP). I was developing a webhook for when a charge fails that would send an email to various departments at my company. We needed the email to have the transaction information and the customer information. Included in the transaction information was the amount… In pennies.

So I needed to convert this to a normal human format. I first used this:

$amount = 12345; // in pennies
setlocale(LC_MONETARY, 'en_US.UTF-8');
money_format('%.2n', $amount); // $12,345.00

But it assumed that I was formatting 12345 dollars. So I had to change to this:

$amount = 12345; // in pennies
$amount = $amount / 100;
setlocale(LC_MONETARY, 'en_US.UTF-8');
money_format('%.2n', $amount); // $123.45

(The amount was coming from the API’s response, so I simplified this for demonstrative purposes.)

Voila! So that’s how you convert an amount from pennies to USD. Let me know if that helped you, could help you, or if you just don’t care either way! 🙂