Format a price based on a user's language in PHP - Formater un prix en fonction de la langue d'un utilisateur en PHP
Publié le .
Here is a function that allows you to display a price formatted according to a user's language and which automatically adds the corresponding currency symbol. Voici une fonction qui permet d'afficher un prix formaté selon la langue d'un utilisateur et qui ajoute automatiquement le symbole monétaire correspondant.
/*
* intl_currency( $price, $lang_locale );
* Function to format a price based on a user's language in PHP
* @param {int/float} $price
* @param {string} $lang_locale - language code to translate (en_US, fr_FR, de_DE, ...)
* @return {string} A price formatted according to the desired language
*/
function intl_currency( $price, $lang_locale ){
// cast in float
$price = (float) $price;
// format price by language
$formatted_price = new NumberFormatter( $lang_locale, NumberFormatter::CURRENCY );
// return: £ 142.23 or 142,23 €, ...
return $formatted_price->formatCurrency( $price,
$formatted_price->getTextAttribute(NumberFormatter::CURRENCY_CODE) );
}
/*
* intl_currency( $price, $lang_locale );
*/
// Examples :
$currency = intl_currency( '1452.36', 'en_GB' );
echo 'English - Great Britain : '.$currency;
echo "\r\n";
$currency = intl_currency( '1452.36', 'en_US' );
echo 'English - United States : '.$currency;
echo "\r\n";
$currency = intl_currency( '1452.36', 'fr_FR' );
echo 'French - France : '.$currency;
echo "\r\n";
$currency = intl_currency( '1452.36', 'fr_CA' );
echo 'French - Canada : '.$currency;
echo "\r\n";
$currency = intl_currency( '1452.36', 'de_DE' );
echo 'Deutsch - Deutschland : '.$currency;
echo "\r\n";
$currency = intl_currency( '1452.36', 'zh-CN' );
echo 'Chinese - China : '.$currency;
// output :
// English - Great Britain : £1,452.36
// English - United States : $1,452.36
// French - France : 1 452,36 €
// French - Canada : 1 452,36 $
// Deutsch - Deutschland : 1.452,36 €
// Chinese - China : ¥1,452.36
// Tip -> list all PHP language codes
// given by Jared at https://www.php.net/manual/en/resourcebundle.locales.php
// print_r(ResourceBundle::getLocales(''));
Mots clés : PHP, price formatted, intl price, price formatted according to a user's language, PHP add currency symbol automatically, PHP afficher un prix formaté selon la langue d'un utilisateur, PHP ajouter le symbole de la monnaie automatiquement