How To Format Currency with PHP on Ubuntu 16.04

Introduction

Formatting currency is an important practice that will help you implement locale-aware visual representions of your pricing text. Using a standard library is an effcient and extensibile way to format your prices to your users.

Using a standard library to format your curreny is helpful in situations where your business expands into a market that doesn’t use your default currency. Formatting your currency with a library is also useful for when you need to show pricing to people in different countries and you’re not sure of the currency symbol to use.

In this tutorial, you will install the PHP Internationalization extension and use it to format a whole number into a presentable format. This extension is a highly portable wrapper around the ICU library that provides formatting and globalization support for software. The extension also provides support for formatting dates and times according to a locale-specific format. It also provides a timezone database which provides information on all the time timezones in the world.

Prerequisites

To complete this tutorial, you’ll need the following:

  • An Ubuntu 16.04 Server with PHP 7.2 installed and a root or sudo user account

Step 1 – Updating Your APT sources list

The PHP international extension is located under the APT package called php7.2-intl. When you install PHP 7.2 packages from the package manager, the prefix will always be php7.2-$X where $X is the extension name. In our case, the extenion name is intl.

This tutorial assumes you have installed PHP 7.2 on your server. If your PHP version is not PHP 7.2, modify the 7.2 part of package name throughout this tutorial.

Update your apt sources by running:

sudo apt-get update

Run the following command to install the extension

sudo apt-get install -y php7.2-intl

Reload the PHP FPM service.

sudo systemctl reload php7-2-fpm.service

Verify the extension is loaded

php -m | grep intl

You should see intl in the output of the above command. You’ve now installed everything needed. Now you can to start using the classes and methods provided by extension.

Step 2 – Using the NumberFormatter library

We will wrap an Invoice object from the Stripe API. Our class will take the Stripe Invoice object as the first argument. You’ll need to install the Stripe PHP Bindings if you haven’t already installed them. Open up a shell and install it with Composer.

composer require stripe/stripe-php

This tutorial assumes your price is stored as a whole number and not a decimal. For example, if $4.00 USD is the price you sell your product for, then whole number amount would be 4000 (4000 cents). This number represents the total number of currency units in the USD currency. The smallest unit of measurement for USD is 1 cent.

By default, Stripe stores the amount value as a whole number (cents), but decimal amounts are also supported



require_once 'vendor/autoload.php';

class Invoice
{
    /**
     * @var \Stripe\Invoice;
     */
    private $invoice;

    /**
     * Represents a Stripe invoice. Pass in the result from `\Stripe\Invoice::retrieve`
     *
     * @param string $stripeObj stripe api Invoice
     *
     * @see https://stripe.com/docs/api/invoices/retrieve?lang=php
     */
    public function __construct(Stripe\Invoice $invoice)
    {
        $this->invoice = $invoice;
    }
}

Next, we’ll define a method to compute the sum of all invoice line items. Our method will return a whole number representing the invoice total. For example, if we charged our customer, $5.00 USD, then our method would return an integer value of 5000.

    
/**
 * Sum all line items in this invoice 
 *
 * @return int
 */
public function getTotal()
{
    $amount = 0;

    foreach ($this->invoice->lines as $line) {
        $amount += $line->amount;
    }

    return $amount;
}

We will use the NumberFormatter class to format your locale-independent whole number to a locale-aware currency display format. This class has 2 required arguments.

The first argument is $locale. For our purposes, we will hard-code en_US, but if your application supports multiple locales, then you would pass in an IETF language tag.

The second argument is a number format style. Since we’re formatting currency, we’ll use the predefined constant NumberFormatter::CURRENCY

/**
 * Get the invoice amount
 *
 * @return string
 */
public function getPresentableAmount()
{
    $formatter = new \NumberFormatter(
        'en_US', 
        \NumberFormatter::CURRENCY
    );

    return $formatter->formatCurrency(
        $this->getTotal() / 100, 
        $this->getCurrency()
    );
}

See the full class on GitHub. Deploy your PHP project to Amezmo in 30 seconds. We make modern PHP deployment, hosting, and scaling easy so you don’t have to waste time setting up servers.