php[world] in Washington, D.C.

NumberFormatter::formatCurrency

numfmt_format_currency

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

NumberFormatter::formatCurrency -- numfmt_format_currencyDar formato a un valor monetario

Descripción

Estilo orientado a objetos

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

Estilo por procedimientos

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

Dar formato al valor monetario según las reglas del formateador.

Parámetros

fmt

Objeto NumberFormatter.

value

El valor numérico monetario.

currency

El código 3-letter ISO 4217 de moneda que indica la moneda a usar.

Valores devueltos

Un string representando el valor de moneda formateado.

Ejemplos

Ejemplo #1 Ejemplo de numfmt_format_currency()

<?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";
?>

Ejemplo #2 Ejemplo orientado a objetos

<?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";
?>

El resultado del ejemplo sería:

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

Ver también

add a note add a note

User Contributed Notes 2 notes

up
9
Ruben
1 year 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
6 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