PHP 8.5.0 Alpha 1 available for testing

NumberFormatter::create

numfmt_create

NumberFormatter::__construct

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

NumberFormatter::create -- numfmt_create -- NumberFormatter::__constructCrea un formateador de números

Descripción

Estilo orientado a objetos (método)

public static NumberFormatter::create(string $locale, int $style, ?string $pattern = null): ?NumberFormatter

Estilo por procedimientos

numfmt_create(string $locale, int $style, ?string $pattern = null): ?NumberFormatter

Estilo orientado a objetos (constructor)

public NumberFormatter::__construct(string $locale, int $style, ?string $pattern = null)

Crea un formateador de números

Parámetros

locale

La configuración local con la cual los números serán formateados (i.e. en_CA).

style

El estilo de formato, una de las constantes de estilo de formato. Si NumberFormatter::PATTERN_DECIMAL o NumberFormatter::PATTERN_RULEBASED es utilizado entonces el formato de número es abierto con el patrón proporcionado, que debe ser compatible con la sintaxis descrita por la » documentación ICU DecimalFormat o » documentación ICU RuleBasedNumberFormat, respectivamente.

pattern

La cadena de patrón, en función del estilo de formato elegido.

Valores devueltos

Devuelve un objeto NumberFormatter o null en caso de error.

Errores/Excepciones

Se levanta una ValueError si locale es inválido.

Historial de cambios

Versión Descripción
8.4.0 Se levanta una ValueError si locale es inválido.
8.0.0 pattern ahora es nullable.

Ejemplos

Ejemplo #1 Ejemplo con numfmt_create::create(), Estilo por procedimientos

<?php
$fmt
= numfmt_create( 'de_DE', NumberFormatter::DECIMAL );
echo
numfmt_format($fmt, 1234567.891234567890000)."\n";
$fmt = numfmt_create( 'it', NumberFormatter::SPELLOUT );
echo
numfmt_format($fmt, 1142)."\n";
?>

Ejemplo #2 Ejemplo con numfmt_create::create(), estilo POO

<?php
$fmt
= new NumberFormatter( 'de_DE', NumberFormatter::DECIMAL );
echo
$fmt->format(1234567.891234567890000)."\n";
$fmt = new NumberFormatter( 'it', NumberFormatter::SPELLOUT );
echo
$fmt->format(1142)."\n";
?>

El resultado del ejemplo sería:

1.234.567,891
millicentoquarantadue

Ver también

add a note

User Contributed Notes 3 notes

up
4
F. Poirotte
15 years ago
When formatting durations using the NumberFormatter::DURATION type, you may also need to use NumberFormatter::setTextAttribute to get the desired output.

<?php

$fmt
= new NumberFormatter('en', NumberFormatter::DURATION);
// Outputs: string(7) "3:25:45"
var_dump($fmt->format(12345));

// "%in-numerals" is the default ruleset, so this results in the same as above.
$fmt->setTextAttribute(NumberFormatter::DEFAULT_RULESET, "%in-numerals");
// Outputs: string(7) "3:25:45"
var_dump($fmt->format(12345));

$fmt->setTextAttribute(NumberFormatter::DEFAULT_RULESET, "%with-words");
// Outputs: string(31) "3 hours, 25 minutes, 45 seconds"
var_dump($fmt->format(12345));

$fmt2 = new NumberFormatter('fr', NumberFormatter::DURATION);
// Outputs: string(7) "12 345"
// See notes below.
var_dump($fmt2->format(12345));

?>

This is a little counter-intuitive because there is not much doc available about the DURATION type.

Also, as far as I can tell, only the English (en) locale has support for the "%in-numerals" & "%with-words" rulesets. Other locales seem to simply format the input as if the DECIMAL type had been used (at least using "fr" or "de" as the target locale).

One way to provide that feature across different locales is to extract the ruleset implicitely used by NumberFormatter::DURATION and adapt it for the locales you're targetting. Use NumberFormatter::getPattern to extract the ruleset.
up
0
igorsantos07
6 years ago
Although there are ORDINAL and SPELLOUT formatters, it's not possible to join these together to turn "2" into "second". You'll either get "2nd", or "two", or something unexpected if you try to use bitwise operators.
up
0
daniel dot rhodes at warpasylum dot co dot uk
13 years ago
It should be noted that the locale string passed into NumberFormatter's constructor doesn't play with UCA keywords quite as readily as, say, the Collator and IntlDateFormatter classes' constructors.

According to the Unicode spec (http://www.unicode.org/reports/tr35), I should be able to specify a locale of "ja_JP@numbers=jpanfin" which, for spellout mode, should give me Japanese financial (ie. anti-forgery) numerals. When passed into NumberFormatter's constructor, "ja_JP@numbers=jpanfin" doesn't work.

However, when I look at a dump of NumberFormatter::getPattern() for the ja_JP locale, I see that the financial numerals *are* in there (as %financial). Here's how we wrangle them out of the NumberFormatter:

<?php
$number
= 1234567890;

$formatter = new NumberFormatter('ja_JP', NumberFormatter::SPELLOUT);

$formatter->setTextAttribute(NumberFormatter::DEFAULT_RULESET, "%financial");

echo
$formatter->format($number);
//above gives [拾弐億参千四百伍拾六萬七千八百九拾] (as opposed to [十二億三千四百五十六万七千八百九十]) - bingo!
?>
To Top