PHP: Format price with currency symbol

Updated: January 10, 2024 By: Guest Contributor Post a comment

Introduction

When dealing with online shops, financial reports, or any application that handles monetary values, properly formatting prices with currency symbols is crucial for clarity and professionalism. In PHP, this task can be approached in several ways, from basic string concatenation to advanced internationalization functions. This tutorial guides you through these methods to format prices with currency symbols proficiently in PHP.

Formatting with String Concatenation

String concatenation is the most straightforward method to append a currency symbol to a price. Imagine you have a price stored in a variable and you want to prep-end a dollar sign to it. You can achieve this with the following code:

$price = 99.99;
$currencySymbol = '

Using NumberFormatter for Localization

If your application serves a global audience, localized currency display becomes essential. PHP’s NumberFormatter class, provided by the Intl extension, facilitates currency formatting for different locales. The following snippet demonstrates how to format a price with the appropriate currency symbol for the US locale:

$formatter = new NumberFormatter('en_US', NumberFormatter::CURRENCY);
$formattedPrice = $formatter->format(99.99);
echo $formattedPrice; // Outputs: $99.99

Keep in mind that the Intl extension may require installation or enabling in your PHP setup.

Custom Currency Symbol Formatting

Sometimes, you may need to format prices with currency symbols that don’t necessarily match the locale’s standard or might even hold custom positions (e.g., after the number). The following example shows how you can achieve custom placement using sprintf:

$price = 99.99;
$symbol = '€';
$localeString = '%2$s%1$.2f'; // Symbol after the price
$formattedPrice = sprintf($localeString, $price, $symbol);
echo $formattedPrice; // Outputs: 99.99€

To put the symbol before the price, simply adjust the order in the format string accordingly.

Handling Multiple Currencies

Applications handling more than one currency type will require a more dynamic approach. A common pattern involves mapping currency codes to their symbols and formatting functions. Here’s an example (that uses a class – the OOP approach):

<?php

class CurrencyFormatter
{
    private static $currencySymbols = [
        'USD' => '$',
        'EUR' => '€',
        'GBP' => '£',
        // Add more currency codes and symbols as needed
    ];

    public static function formatAmount(float $amount, string $currencyCode): string
    {
        if (!array_key_exists($currencyCode, self::$currencySymbols)) {
            return 'Invalid Currency Code';
        }

        $symbol = self::$currencySymbols[$currencyCode];
        $formattedAmount = number_format($amount, 2); // Format amount with two decimal places

        return $symbol . $formattedAmount;
    }
}

// Example usage
$amount = 100.50;
$usdFormatted = CurrencyFormatter::formatAmount($amount, 'USD');
$eurFormatted = CurrencyFormatter::formatAmount($amount, 'EUR');

echo 'Amount in USD: ' . $usdFormatted . PHP_EOL;
echo 'Amount in EUR: ' . $eurFormatted . PHP_EOL;

In this example, the CurrencyFormatter class contains a static array $currencySymbols that maps currency codes to their symbols. The formatAmount method takes an amount and a currency code as input, checks if the currency code is valid, and then formats the amount with the corresponding currency symbol. The example usage demonstrates formatting amounts for USD and EUR. You can extend the $currencySymbols array to include more currency codes and symbols as needed.

Currency Formatting in E-Commerce Systems

In e-commerce systems, price formatting goes hand in hand with product price display, checkout processes, and invoices. This section outlines how you could integrate localized formatting and even display prices in different currencies based on user preferences. Assume your e-commerce system has a product class:

class Product {
    protected $price;
    protected $currency;

    public function __construct($price, $currency = 'USD') {
        $this->price = $price;
        $this->currency = $currency;
    }

    public function displayPrice() {
        $formatter = new NumberFormatter('en_US', NumberFormatter::CURRENCY);
        return [$this->currency => $formatter->formatCurrency($this->price, $this->currency)];
    }
}

$product = new Product(25.00); 
$formattedPrice = $product->displayPrice();
foreach ($formattedPrice as $currency => $price) {
    echo "$currency: $price
"; // Outputs: USD: $25.00 }

This approach can be adapted to achieve multi-currency support, complete with conversion rates.

Debugging and Error Handling

Issues can arise during the currency formatting process. Working with PHP’s error handling, ensure your code addresses potential exceptions, particularly when dealing with the Intl extension or external APIs for currency conversion. Below is a way to gracefully handle errors:

try {
    $formatter = new NumberFormatter('fr_FR', NumberFormatter::CURRENCY);
    $formattedPrice = $formatter->format(99.99);
    if ($formattedPrice === false) {
        throw new Exception('Currency formatting failed: ' . intl_get_error_message());
    }
    echo $formattedPrice;
} catch (Exception $e) {
    echo 'Error: ' . $e->getMessage();
}

Conclusion

Formatting prices with currency symbols is more than just aesthetic; it’s required for clear communication and to avoid confusion about monetary amounts. Whether your application is small and regional or large-scale and international, PHP provides the tools necessary to display prices accurately and professionally. Remember to use locale-aware methods for international audiences and reliably handle errors for robust and user-friendly applications.