PHP Unconference Europe 2015

NumberFormatter::formatCurrency

numfmt_format_currency

(PHP 5 >= 5.3.0, PECL intl >= 1.0.0)

NumberFormatter::formatCurrency -- numfmt_format_currencyFormate une valeur monétaire

Description

Style orienté objet

public string NumberFormatter::formatCurrency ( float $value , string $currency )

Style procédural

string numfmt_format_currency ( NumberFormatter $fmt , float $value , string $currency )

Formate une valeur monétaire, en fonction des règles du formateur.

Liste de paramètres

fmt

L'objet NumberFormatter.

value

La valeur numérique.

currency

Le code à trois lettres ISO 4217 de la devise à utiliser.

Valeurs de retour

La chaîne représentant la valeur formatée.

Exemples

Exemple #1 Exemple avec numfmt_format_currency(), Style procédural

<?php
$fmt 
numfmt_create'de_DE'NumberFormatter::CURRENCY );
echo 
numfmt_format_currency($fmt1234567.891234567890000"EUR")."\n";
echo 
numfmt_format_currency($fmt1234567.891234567890000"RUR")."\n";
$fmt numfmt_create'ru_RU'NumberFormatter::CURRENCY );
echo 
numfmt_format_currency($fmt1234567.891234567890000"EUR")."\n";
echo 
numfmt_format_currency($fmt1234567.891234567890000"RUR")."\n";
?>

Exemple #2 Exemple avec numfmt_format_currency(), style POO

<?php
$fmt 
= new NumberFormatter'de_DE'NumberFormatter::CURRENCY );
echo 
$fmt->formatCurrency(1234567.891234567890000"EUR")."\n";
echo 
$fmt->formatCurrency(1234567.891234567890000"RUR")."\n";
$fmt = new NumberFormatter'ru_RU'NumberFormatter::CURRENCY );
echo 
$fmt->formatCurrency(1234567.891234567890000"EUR")."\n";
echo 
$fmt->formatCurrency(1234567.891234567890000"RUR")."\n";
?>

L'exemple ci-dessus va afficher :

1.234.567,89 €
1.234.567,89 RUR
1 234 567,89€
1 234 567,89р.

Voir aussi

add a note add a note

User Contributed Notes 2 notes

up
9
Ruben
2 years ago
While this function accepts floats for currency (in order to display cents), you should (for applications where this is critical) never store or handle money using floats, as rounding errors may occur. Work with integers (or a BigInt class if integers aren't large enough) internally instead, where the integer represents the total number of cents. An alternative (especially if you need more precision than cents) is using the BC (Binary Calculator) Math module, that handles arbitrary precision numbers with 100% accuracy.
up
1
martin t holzhauer dohd eu
8 months ago
When you want to format currency's without sub units and the currency is not the one used by the given locale you need to set the currency code before as TextAttribute _BEFORE_ setting the NumberFormatter::FRACTION_DIGITS

<?php
$fmt
= new NumberFormatter('en_US', NumberFormatter::CURRENCY);
$fmt->setTextAttribute(NumberFormatter::CURRENCY_CODE, 'EUR');
$fmt->setAttribute(NumberFormatter::FRACTION_DIGITS, 0);
$fmt->formatCurrency(100, 'EUR');
?>
To Top